I start off my game with all object’s mesh renderer’s turned off. When the player collides with the mesh renderer, I have it to be turned on. How would I start a “timer,” so that after a certain duration after colliding, the objects mesh renderer would turn off and become invisible again until the next collision? I started reading things into Couroutines and IEnumerators, but am still really confused.
Also just wanted to note that I am very new and have little unity experience so anything would be greatly appreciated!
Hi, if I wanted to make an object appear after a collision and then disappear after a certain amount of time i would do this:
public class TurnOnMeshRendererAfterCollision : MonoBehaviour// "TurnOnMeshRendererAfterCollision" is the class name
// the amount of time spent on after collision. the f after the 1 is to tell unity that it is a float
public float upTime = 1f;
private MeshRenderer m_MeshRenderer; // our mesh renderer
private float timerStart; // this will store our timer's start time
void Awake()// Awake() runs before start which runs when the script starts running
m_MeshRenderer = GetComponent<MeshRenderer>(); // assign the m_MeshRenderer variable to the mesh renderer on this object
// OnTriggerEnter runs every time this object's collider which must be set as trigger collides with something
void OnTriggerEnter(Collider other) // other is the other collider we are colliding with
// now that we have collided with something we will enable the mesh renderer and start the timer
m_MeshRenderer.enabled = true;
// set time start to the game time ie. if the has been running for 2 minutes timerStart will now be 2 minutes
timerStart = Time.realtimeSinceStartup; // this will record the time that the collision happened
// Update is called once per frame
// check to see if it is time to turn of the mesh renderer
if (Time.realtimeSinceStartup - timerStart > upTime) // by subtracting the current time from the time the timer started we can get the amount of time between them
// we now know that the time since the collision happened is greater than the amount of time foe the mesh renderer to be on
// we will turn it off
m_MeshRenderer.enabled = false;
you should be able to just copy and paste this into your project just make sure that the class name and the file name match. and put this script on any object you want to make appear and disappear
Hope this helps!