How to activate an object after "x" seconds (C#)?
Hallo all. I know only the bare minimum of how coding works, so please bear with me!
I have a row of lights that I need to turn on for a second, then turn off. After three seconds, they should turn back on again, then turn off after a second, and repeat. Actually, there are three rows and they should be staggered, but I think I know how to do that using WaitForSeconds.
What I haven't figured out is how to do enable/disable a component after a set time in the first place. I'd post my attempt at coding it, but it probably wouldn't help you anyways. Thanks for any help!
Answer by UnityCoach · Apr 17, 2017 at 10:17 AM
You could do all this with Animations and Animator Controllers too! "enabled" properties are animatable.
This solution seemed to work the simplest. Thanks!
Answer by Cuttlas-U · Apr 17, 2017 at 06:59 AM
hi; if u already know how to wait disabling or enabling of a component is not much of work;
u just get that component and disable it or not like this:
if your compoentn name is "Movement" then ..
GetComponent<Movement>().enabled = false;
and u can make it true this way too;
if the component is attached to different object u first need to access that object then get the component :
for example if your object name is "rows 1" then :
GameObject.Find("rows 1").GetComponent<Movement>().enabled = false;
Answer by Skyking · Apr 17, 2017 at 08:33 AM
Hey,
Will let people know how to wait for seconds before an event (in response to the question, so others searching for the answer will find this). Cuttlas-U already explained how to enable/disable scripts.
A coroutine is what you are looking for: https://docs.unity3d.com/ScriptReference/Coroutine.html
Example script (attach this script to an object in your scene): public class ExampleClass : MonoBehaviour { IEnumerator WaitAndPrint() { // suspend execution for 5 seconds yield return new WaitForSeconds(5); print("WaitAndPrint " + Time.time); } }
Some other coroutine 'wait' options: yield return new WaitForEndOfFrame()
yield return new WaitForFixedUpdate()
yield return new WaitForSeconds(float seconds)
yield return new WaitForSecondsRealtime(float seconds)
yield return new WaitUntil(bool predicate)
yield return new WaitWhile(bool predicate)
Answer by RealGamesStudio · Apr 17, 2017 at 08:10 PM
Hello! You can try doing this with Invoke
Just create the activation method for enable/disable and with Invoke you can start the method after the time you want.
Invoke ("methodName", 1)
You can read more about Invoke on the Unity Learn page. If you want everything to repeat, you can use InvokeRepeating instead of just Invoke. I think that its suitable for your situation. I hope that helps! I wish you a great week! :))