Multiple objects being instantiated instead of one
Hey guys, I'm working on a project where an object (a fish picked randomly from an array) spawns after a delay. This process of spawning after a delay only happens when the previous object has been destroyed. The problem I'm having is that several fish are spawning instead of one when the co-routine runs, I'm assuming they spawn per frame for a whole second before stopping. I just want one fish to spawn instead of 50-60. Can someone show me what I'm doing wrong please??
Here's a sample of my code currently:
void Update ()
{
thisTransform = transform.position;
FishCheck ();
if (hasFish == false && transform.childCount == 0)
{
StartCoroutine (FishRespawn ());
}
}
IEnumerator FishRespawn ()
{
yield return new WaitForSeconds (spawnDelay);
GameObject spawnedFish = Instantiate (fishArr[Random.Range(0,fishArr.Length)], thisTransform, Quaternion.Euler(0, 0, 0));
spawnedFish.transform.SetParent (this.gameObject.transform);
spawnedFish.transform.localScale = new Vector3(0.53f, 0.53f, 0.53f);
spawnedFish.transform.localRotation = Quaternion.Euler(transform.rotation.x, -180f, 0f);
yield break;
}
void FishCheck ()
{
if (transform.childCount == 0)
{
hasFish = false;
}
if (transform.childCount == 1)
{
hasFish = true;
}
if (transform.childCount > 1)
{
hasFish = true;
}
}
void OnTriggerExit (Collider col)
{
if (col.gameObject.tag == "Fish")
{
hasFish = false;
}
}
Thank you
Your answer
Follow this Question
Related Questions
Bullets with raycast and physics 2 Answers
Unity Freezing after for loop 1 Answer
Insantiate Loop Issue 0 Answers
Why sprite doesn't change without coroutine? 1 Answer
Setting transform position in Coroutines - not updating when expected? 0 Answers