How to execute code after X seconds
Hello. I know this question has been asked before but i couldnt get it to work properly I am new in Unity and really bad at coding so that's why I am asking something so obvious for some people like this... :(
I have this code, in my FPS game, that i found on Youtube, where i want to give me ammo every 3 seconds if i come to the area. To specify this area I use a collider box. So i want to have this code executed every 3 seconds when being in the area that i mentioned above..
This is the code: var AmmoPickUpSound : AudioSource;
function OnTriggerEnter (col : Collider) {
AmmoPickUpSound.Play();
if (GlobalAmmo.LoadedAmmo == 0) {
GlobalAmmo.LoadedAmmo += 30;
}
else {
GlobalAmmo.CurrentAmmo += 30;
}
}
I don't know javascript, just C#.
What I would do is have a separate method for increasing ammo. within the method would be
if (!bool$$anonymous$$oreAmmo){
invokeRepeating (methodname, delay, repeat time);
bool$$anonymous$$oreAmmo = true;
}
and
OnTriggerExit (col : Collider ){ CancelInvoke (methodname); bool$$anonymous$$oreAmmo = false; }
Tried to avoid filling this with C#, does that help?
Answer by enosoft · Dec 28, 2020 at 11:52 AM
u can using this
StartCoroutine(passiveMe(5));
IEnumerator passiveMe(int secs)
{
yield return new WaitForSeconds(secs);
gameObject.SetActive(false);
}
Answer by DoomSlayer1995 · Sep 22, 2017 at 08:11 PM
InvokeRepeating: http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.InvokeRepeating.html
Use it to execute the code the time you need.