HOW TO PERFORM FUNCTION EVERY TIME PERIOD - UNITY

Asked

Viewed 414 times

1

I need to perform this function - which creates a randomized platform in a randomized position - every 3 seconds . How does??


void CreatePlatform()
{
      System.Random random = new System.Random();
      int vectorNumber = random.Next(0, 5);

      Vector3 position = new Vector3(0, UnityEngine.Random.Range(-6.0f, 6f), 0);

      Instantiate(plataforms[VectorNumber], position, Quaternion.Euler(new Vector3(6,6,0)));        
    } 

Thank you.

1 answer

2


Use the function InvokeRepeating(string methodName, float time, float repeatRate);

The first parameter is the method you want to call.

The second parameter is the waiting time before calling the function for the first time.

The third parameter is the time interval to call the function repeatedly.

In your case it would look like this:

public class Foo : MonoBehaviour
{
    void Start()
    {
        InvokeRepeating("CreatePlatform", .01f, 3f);
    }

    void CreatePlatform()
    {
        System.Random random = new System.Random();
        int vectorNumber = random.Next(0, 5);

        Vector3 position = new Vector3(0, UnityEngine.Random.Range(-6.0f, 6f), 0);

        Instantiate(plataforms[VectorNumber], position, Quaternion.Euler(new Vector3(6,6,0)));        
    } 
}

For more details, see the Unity documentation: https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html?_ga=2.239218051.1201192954.1593687853-1815494055.1593687853

Browser other questions tagged

You are not signed in. Login or sign up in order to post.