Menu
CoddyTech

Keeping Score

Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 29 of 63.

challenge icon

Challenge

Medium

Count 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 field public int score; and a method public void AddScore(int points) that adds points to score and logs the new total as Score: 4.
  • In Coin: a field public int value = 1;. The Inspector sets the big coin's to 3.
  • When the ball collects a coin, the coin calls the ball's AddScore with its value, 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