ALright, I have a basic gun, just to test my abilities, but I want to make a wait thingy, so 2 secs later I have ammo. How would I make a wait thingy? (I have tried waitforseconds no mater what I do it errors) ALso please try to make it like one line short. This is in CShrap, and is under void update()
It’s easy once you get past all the oddly named functions:
You need to keep a flag in your update: bool waitingToReload
if(waitingToReload != true){
StartCoroutine(fireGun( waitingTime ));
}
make your waitingTime 2 seconds or whatever. Then declare an IEnumerator function. check the tutorial, they are good to learn from.
IEnumerator fireGun(float waitTime){
waitingToReload = true;
//you can do other stuff here too
yield return new WaitForSeconds (waitTime);
//or you can do it here too
waitingToReload = false;
}
You can’t yield in Update(). You must use Invoke, or InvokeRepeating to invoke a function, or use a Coroutine.
Invoke Example:
using UnityEngine;
using System.Collections;
public class InvokeExample : MonoBehaviour
{
void Start()
{
Invoke ("Count", 3);
}
void Count()
{
print ("Count function invoked!");
}
}
InvokeRepeating Example:
using UnityEngine;
using System.Collections;
public class InvokeRepeatingExample : MonoBehaviour
{
int count = 0;
void Start()
{
InvokeRepeating("Count", 1, 1);
}
void Count()
{
count++;
print (count);
}
}
Coroutine Example:
using UnityEngine;
using System.Collections;
public class CoroutineExample : MonoBehaviour
{
int count = 0;
void Start()
{
StartCoroutine(Count ());
}
IEnumerator Count()
{
while(true)
{
count++;
print (count);
yield return new WaitForSeconds(1);
}
}
}
Say you want to fire by clicking left mouse, then wait 1 second before you may fire again, here’s how you’d do that using a Coroutine, my method of choice in this case.
using UnityEngine;
using System.Collections;
public class WaitToFireExample : MonoBehaviour
{
bool canFire = true;
void Update()
{
if(canFire && Input.GetMouseButtonDown(0))
{
canFire = false;
StartCoroutine (WaitToFire(1));
}
}
IEnumerator WaitToFire(float t)
{
print (canFire);
yield return new WaitForSeconds(t);
canFire = true;
print (canFire);
}
}