- Home /
i resolved the problem
script not working :(
hi im tring to make a game but this scrpt isnt working its ment to be a gather over time recorse script so i gets ammo every 5 seconds then another piece till it gets to max but it desnt collect unless its in the update but i cant use the wait for seconds in update how can i fix
public int AmmoRec = 0;
public int MaxAmmoRec = 500;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Add ();
}
IEnumerator Add(){
if (AmmoRec < MaxAmmoRec) {
yield return new WaitForSeconds (5.0f);
AmmoRec ++ ;
} else if (AmmoRec == MaxAmmoRec) {
AmmoRec = MaxAmmoRec;
}
Debug.Log (AmmoRec);
}
Answer by tanoshimi · Oct 14, 2016 at 05:25 PM
public int AmmoRec = 0;
public int MaxAmmoRec = 500;
void Start () {
InvokeRepeating("Add", 0f, 5f);
}
void Add(){
if (AmmoRec < MaxAmmoRec) {
AmmoRec ++ ;
}
}
Answer by Naphier · Oct 14, 2016 at 05:28 PM
Well, you could start by watching some tutorial videos on coding to learn a bit about how IEnumerators (coroutines) work in Unity. First, you need to call StartCoroutine(Add()) -- that will run the coroutine (do this in your start method, NOT in Update()). Second, the coroutine will need a loop (such as while) to continue executing in a loop. Or you could use InvokeRepeating on any void method.
Follow this Question
Related Questions
Time Manager Class Implementation Like Coroutine in Unity 1 Answer
Object over terrain 2 Answers
increase over time 1 Answer
How to change value of variable over period of time? 2 Answers
Loading Screen and Lerp 3 Answers