Trying to spawn random falling rocks, can't figure out why it's not working. Help would be appreciated!
I am making a 2D adventure game. In one level, the player is faced with a chamber full of rocks that are falling from above screen height and down to the ground the player is on, and kills the player if one hits him.
The problem I am having is the delay between rock spawns. I tried an IEnumerator function called after every rock spawn, but it doesn't seem to work. Unity just freezes when I run the code.
Here is my full code:
using UnityEngine;
using System.Collections;
public class SpawnRocks : MonoBehaviour {
public static Transform rockSpawn;
public GameObject[] rocks;
int spawnSpot;
void Start () {
SpawnRock();
}
void Update () {
}
void SpawnRock() {
//change up spawn position of rocks a bit
spawnSpot = Random.Range(-1, 8);
//pick a random rock prefab from our array of prefabs, copy it to the new theRock object
GameObject theRock = rocks[Random.Range(0, rocks.Length)];
//spawn theRock
Instantiate(theRock, new Vector3(transform.position.x + spawnSpot, transform.position.y, transform.position.z), Quaternion.identity);
//give it a random direction and velocity
theRock.GetComponent<Rigidbody2D>().velocity = ((Vector2)Random.onUnitSphere).normalized * Random.Range(5, 10);
//destroy theRock after 2 seconds
Destroy(theRock, 2f);
//wait for a random amount of seconds
Wait();
//spawn another rock
SpawnRock();
}
public static IEnumerator Wait() {
yield return new WaitForSeconds(Random.Range(.2f,.5f));
}
}
If I delete the recursive SpawnRock(); call at the bottom, and take out SpawnRock(); from the Start function, then add it to just Update(), rocks just continually spawn until the game lags out. I know it must be something wrong with my Wait function, but I cannot find out what.
Any help is much appreciated! Thank you in advance.
Answer by Landern · Sep 16, 2016 at 12:41 PM
You should use StartCoroutine in combination with WaitForSeconds to create a continuation for x seconds, currently as you stated it will just keep going over and over. It's better to use the Update/FixedUpdate methods to execute these functions, but either way, StartCoroutine is your friend. Optionally InvokeRepeating
Answer by NerdClown · Sep 16, 2016 at 12:45 PM
I think the problem is here:
//wait for a random amount of seconds
Wait();
This does not actually wait for a number of second before moving to the next instruction. You can use it to get a similar behavior with coroutines.
Here's an example of recursion made using coroutines in Unity.
And here is some unity documentation for the coroutine thing, with a bunch of examples in there.