Menu
CoddyTech

Keeping Score

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 30 of 71.

challenge icon

Challenge

Medium

Count the coins: each coin knows its value, and the ball keeps the total.

  1. In Ball.cs, add public int score; and public void AddScore(int points), which adds points and logs "Score: " + score.
  2. In Coin.cs, add public int value = 1;. The big coin's is 3.
  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

Practice on your own: Unity playground