Coins Come Back
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 30 of 63.
Challenge
MediumA 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 itsRenderer, so it is not drawn, and itsCollider, so it cannot be collected again. - On collection, start a coroutine that hides the coin, waits
respawnDelayseconds, 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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to Collect