Picking up an item and spawning a new one.
I'm currently trying to create a slightly more advanced version of the Unity 'Roll A Ball' tutorial. Specifically, I am trying to create a feature in which the 'Pick Up' objects will spawn around my playable area one at a time, to a maximum of 5 objects in the game at one time. With my current code, I am able to have the objects spawn in random areas and indeed to a maximum of 5, but once the game has spawned 5 objects it won't spawn anymore, despite some of the objects having been collected or deleted (Meaning there would be less than 5 in the game at one time). I'm fairly new to C# and so I wouldn't be surprised if my code is a bit rubbish :P. Thanks to anyone that can help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnPickup : MonoBehaviour {
public int maxNumObjects = 5;
public GameObject objectToSpawn;
public float rangeX_Negative = -5f;
public float rangeX_Positive = 5f;
public float rangeZ_Negative = -5f;
public float rangeZ_Positive = 5f;
public float respawnTimer = 5f;
// Use this for initialization
void Start()
{
StartCoroutine(SpawnTimer());
}
IEnumerator SpawnTimer()
{
for (int i = 0; i < maxNumObjects; i++)
{
Spawn();
yield return new WaitForSeconds(respawnTimer);
}
}
void Spawn()
{
float randomX = Random.Range(rangeX_Negative, rangeX_Positive);
float randomZ = Random.Range(rangeZ_Negative, rangeZ_Positive);
Instantiate(objectToSpawn, new Vector3(randomX, 0.75f, randomZ), Quaternion.identity);
}
}
I also tried to add the following code in place of the SpawnTimer function code, but it still didn't work. (Not sure I got this code right though)
if(maxNumObjects < 0)
{
Spawn();
yield return new WaitForSeconds(respawnTimer);
}