Menu
CoddyTech

Coins Come Back

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

challenge icon

Challenge

Medium

A collected coin comes back after respawnDelay seconds, so there is always something to chase. That is a wait inside one coin's life: a coroutine. Keep everything from the earlier steps, and change Coin:

  • Add public float respawnDelay = 3f;.
  • A deactivated GameObject runs no coroutines, so SetActive(false) would stop the coin's coroutine before it could bring the coin back. Hide the coin another way: turn off its Renderer, so it is not drawn, and its Collider, so it cannot be collected again.
  • On collection, start a coroutine that hides the coin, waits respawnDelay seconds, then turns both back on. The score is added as before.

Press Play, collect a coin and watch it return, then Check.

Try it yourself

using UnityEngine;

public class Coin : MonoBehaviour
{
    public int value = 1;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            other.GetComponent<Ball>().AddScore(value);
            gameObject.SetActive(false);
        }
    }
}

All lessons in Physics and Gameplay