Coins Come Back
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 31 of 71.
Challenge
MediumBring a collected coin back after respawnDelay seconds.
- In
Coin.cs, addusing System.Collections;andpublic float respawnDelay = 3f;. - Write
IEnumerator Respawn(): turn offGetComponent<Renderer>().enabledandGetComponent<Collider>().enabled, waitrespawnDelay, then turn both on. - Replace
gameObject.SetActive(false);withStartCoroutine(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
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall5Project: Coin Rush
The Rolling BallCoins to CollectPractice on your own: Unity playground