Home > Software engineering >  How do we run a program in every X seconds in unity
How do we run a program in every X seconds in unity

Time:07-30

so basically what i wanted to do is to teleport my cube every X seconds, and this is what ive done:

public class Teleport_Cube : MonoBehaviour
{
    public Transform cubepos; //my cube postition
    public List<Transform> transforms = new List<Transform>();


    void Start()
    {   
        int pos = Random.Range(0, transforms.Count); // Code i wanted to execute after X seconds
        cubepos.position = transforms[pos].position; // Code i wanted to execute after X seconds
        StartCoroutine(waitforsec(5));
    }

    IEnumerator waitforsec(float seconds)
    {
        yield return new WaitForSeconds(seconds);
    }

}

and it didnt seems to work, it just teleport once and stay.

Ive done it inside the void Update method too and it just teleport every frame.

maybe you can help me to find the solution?? Tysm! have a nice day:)

CodePudding user response:

You can use the InvokeRepeating() method to achieve your goal

void Start()
{
    InvokeRepeating("TeleportCube", 0, 5.0f);
}

void TeleportCube()
{
    int pos = Random.Range(0, transforms.Count); // Code i wanted to execute after X seconds
    cubepos.position = transforms[pos].position; // Code i wanted to execute after X seconds
}

CodePudding user response:

The reason it is teleporting once, is because it is only being called once in the Start function. Here is what you need to do.

public class Teleport_Cube : MonoBehavior 
{
    public Transform cubepos; //my cube postition
    public List<Transform> transforms = new List<Transform>();

    void Start()
    {  
    StartCoroutine(myStart());
    }

    IEnumerator myStart() {
        while(true) {
            int pos = Random.Range(0, transforms.Count); // Code i wanted to execute after X seconds
            cubepos.position = transforms[pos].position; // Code i wanted to execute after X seconds
            StartCoroutine(waitforsec(5))
        }
        yeild return null;
    }

    IEnumerator waitforsec(float seconds)
    {
        yield return new WaitForSeconds(seconds);
    }

}

The myStart function will repeat forever, or for as long as whatever you put in the while loop to be false.

  • Related