- Home /
My loop isn't working??? (C#) (Need help please)
I'm trying to make a loop that infinity duplicates a cube every 3 seconds but it won't work??? (C#)
using UnityEngine;
using System.Collections;
public class MoveSpawner : MonoBehaviour {
public Transform DupedCube;
public Transform CubeSpawner;
public float Speed = 2.0f;
// Update is called once per frame
void Update ()
{
CubeSpawner.transform.position = new Vector3(Mathf.PingPong(Time.time * Speed, 19), CubeSpawner.transform.position.y, CubeSpawner.transform.position.z);
}
void Start()
{
StartCoroutine(Dupe());
}
IEnumerator Dupe()
{
yield return new WaitForSeconds(3);
var x = Instantiate(DupedCube, CubeSpawner.transform.position, CubeSpawner.transform.rotation);
}
}
try this
IEnumerator Dupe() { yield return new WaitForSeconds(3); var x = Instantiate(DupedCube, CubeSpawner.transform.position, CubeSpawner.transform.rotation);
StartCoroutine(Dupe()); }
Wouldn't you get a stack overflow with this? I'm actually not sure if starting coroutines puts them on stack, but for infinite coroutine would be better done be putting the body in while(true) loop.
Also that should not be 'true' but some actual bool if you by any chance would ever want to stop that loop
No that wouldn't cause a stackoverflow since StartCoroutine will return when the new coroutine hits the first yield. So the starting coroutine can finish properly. $$anonymous$$eep in $$anonymous$$d that coroutines are not methods but statemachine objects. So starting a new coroutine would work.. However as you said this is not recommended. Starting a coroutine will create a new instance of the statemachine. Using a loop is the way better approach.
Note you don't really need a boolean. When you store the coroutine in a variable you could stop it whenever you want. Apart from that there's also the StopAllCoroutines method.
Answer by Bunny83 · Sep 09, 2018 at 02:04 AM
As already said in the comments, you don't have any loop in your coroutine. You start it once in start and it only runs once. If you want the code to loop you need an actual loop like that:
IEnumerator Dupe()
{
while(true)
{
yield return new WaitForSeconds(3);
var x = Instantiate(DupedCube, CubeSpawner.transform.position, CubeSpawner.transform.rotation);
}
}