Keeping Score
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 29 of 63.
Challenge
MediumCount the coins. Each coin knows what it is worth, and the ball keeps the total. Keep everything from the earlier steps, and add:
- In
Ball: a fieldpublic int score;and a methodpublic void AddScore(int points)that addspointstoscoreand logs the new total asScore: 4. - In
Coin: a fieldpublic int value = 1;. The Inspector sets the big coin's to 3. - When the ball collects a coin, the coin calls the ball's
AddScorewith itsvalue, then hides as before.
Press Play and collect them all for 7 points, then Check.
Try it yourself
using UnityEngine;
public class Ball : MonoBehaviour
{
public float force = 10f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
rb.AddForce(new Vector3(x, 0f, z) * force);
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to Collect