- Home /
How to make repeateRate random in "InvokeRepeating"
public class SpawnToken : MonoBehaviour
{
public GameObject tokenPrefab;
private Vector3 spawnPosition;
private float startDelay = 1.0f;
private float repeatRate = 2.0f;
private float spawnRangeX = 4.3f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("Spawn", startDelay, repeatRate);
}
// Update is called once per frame
void Update()
{
}
public void Spawn()
{
spawnPosition = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 8.0f, -0.762f);
Instantiate<GameObject>(tokenPrefab, spawnPosition, tokenPrefab.transform.rotation);
Debug.Log(repeatRate);
}
}
I've tried to set repeatRate = Random... initially but that doesn't work.
I also tried to set it in the Spawn method / Update the same result.
Answer by Larry-Dietz · Dec 01, 2019 at 11:26 PM
First thought that comes to mind would be to change your InvokeRepeating to Invoke, so it only calls it the one time, after your delaytime.
Then, as the last line of the Spawn event, call Invoke again, with a random number for the time.
Hope this helps, -Larry
Answer by davidmiltonmclean · Dec 01, 2019 at 11:42 PM
YES! it worked.
void Start()
{
Invoke("Spawn", 3.0f);
}
public void Spawn()
{
spawnPosition = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 8.0f, -0.762f);
Instantiate<GameObject>(tokenPrefab, spawnPosition, tokenPrefab.transform.rotation);
Invoke("Spawn", Random.Range(20.0f, 30.0f));
Debug.Log(repeatRate);
}
I set the numbers high to test the change, and it worked! Thank you so much. Learning unity so I don't know a lot yet but it's very cool that I can get help so quickly.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is Random.Range() Really Maximally Inclusive? 4 Answers
Image for a quarter of a second 1 Answer