Menu
CoddyTech

Coins Come Back

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

challenge icon

Challenge

Medium

Bring a collected coin back after respawnDelay seconds.

  1. In Coin.cs, add using System.Collections; and public float respawnDelay = 3f;.
  2. Write IEnumerator Respawn(): turn off GetComponent<Renderer>().enabled and GetComponent<Collider>().enabled, wait respawnDelay, then turn both on.
  3. Replace gameObject.SetActive(false); with StartCoroutine(Respawn());: an inactive object runs no coroutines.

Press Play and collect a coin: it returns 3 seconds later. 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

Practice on your own: Unity playground