- Home /
Instatiate object in every given second problem C#
Hello. I'd like to instantiate object in every given second. I read some articles and found the solution, but it doesn't work for me. Could you help me find the problem?
Error: Assets/Scripts/Spawner.cs(14,45): error CS1525: Unexpected symbol (', expecting
)', ,',
;', [', or
='
Here is my code:
public class Spawner : MonoBehaviour {
public GameObject spawnedObject;
public float begin;
public float end;
public float timeDelay = 2;
void Start() {
float y = Random.Range(begin,end);
while(true){
Instantiate(spawnedObject, new Vector3(-11,y,0), Quaternion.identity);
yield WaitForSeconds(timeDelay);
}
}
}
Answer by JChilton · Mar 21, 2014 at 05:34 PM
Your issue is that you're in C#, and using the yield function incorrectly. You want to either use a repeating Invoke, or a coroutine to wait your time delay.
void Start(){
StartCoroutine(SpawnEachSecond());
}
IEnumerator SpawnEachSecond(){
while(true){
float y = Random.Range(begin,end);
Instantiate(spawnedObject, new Vector3(-11,y,0), Quaternion.identity);
yield return new WaitForSeconds(timeDelay);
}
}
Perfect solution, thanks :) I tried to make C# from js incorretly.
Answer by supernat · Mar 21, 2014 at 05:33 PM
Well line 14 is closing bracket }. It might help if you post what line 14 is in your code to help us out. But I do see a couple of things wrong. "yield WaitForSeconds(...)" should be "yield return new WaitForSeconds(...)". Also, to use Start as a coroutine, you have to define start as "IEnumerator Start()".
Your answer
![](https://koobas.hobune.stream/wayback/20220613140830im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Repetitive task within a fixed timeframe? 0 Answers