- Home /
Question by
ajcj · Nov 24, 2019 at 10:32 PM ·
instantiate
InvokeRepeating for random ball spawn
So I want to randomly spawn ball in the environment. I have the following code (and its not giving the randomness that I want). Please explain what I'm not doing correctly.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SpawnManagerX : MonoBehaviour { public GameObject[] ballPrefabs;
private float spawnLimitXLeft = -22;
private float spawnLimitXRight = 7;
private float spawnPosY = 30;
private float startDelay = 1.0f;
private float spawnInterval = 8.0f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnRandomBall", Random.Range(startDelay,9.0f), Random.Range(2.0f,spawnInterval));
}
// Spawn random ball at random x position at top of play area
void SpawnRandomBall ()
{
// Generate random ball index and random spawn position
Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);
// instantiate ball at random spawn location
Instantiate(ballPrefabs[Random.Range(0,2)], spawnPos, ballPrefabs[0].transform.rotation);
}
}
Comment
Answer by prof · Nov 26, 2019 at 05:58 AM
InvokeRepeating interval is not going to change once you called it. You can do this for expamle
public class Test : MonoBehaviour{
private bool stopRepeating = false;
void Start(){
Invoke(nameof(RepeatingFunction), Random.Range(1.0f, 3.0f));
}
void RepeatingFunction(){
if (stopRepeating) return;
Debug.Log("Do stuff");
Invoke(nameof(RepeatingFunction), Random.Range(1.0f, 10.0f));
}
}