Keeping Score
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 30 of 71.
Challenge
MediumCount the coins: each coin knows its value, and the ball keeps the total.
- In
Ball.cs, addpublic int score;andpublic void AddScore(int points), which addspointsand logs"Score: " + score. - In
Coin.cs, addpublic int value = 1;. The big coin's is 3. - On collection, call
other.GetComponent<Ball>().AddScore(value);before hiding the coin.
Press Play and collect every coin: the Console reaches Score: 7. 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 Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to CollectPractice on your own: Unity playground