Answer the question
In order to leave comments, you need to log in
Why does the script work incorrectly in Unity?
Here is the code itself, not when you start the game, a billion cars appear, tell me what is the problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class makecar : MonoBehaviour
{
public GameObject[] cars;
private float[] positions = { 0, -3.13f, 3.13f };
public GameObject mainButtons;
void Start()
{
StopCoroutine(spawn());
}
public void Update()
{
if (mainButtons.activeSelf == true)
{
StopCoroutine(spawn());
}
else if (mainButtons.activeSelf == false)
{
StartCoroutine(spawn());
}
}
IEnumerator spawn()
{
while (true)
{
Instantiate
(cars[Random.Range(0, cars.Length)],
new Vector3(positions[Random.Range(0, 3)], 0, -9.5f),
Quaternion.Euler(new Vector3(0, 180, 0))
);
yield return new WaitForSeconds(2.5f);
}
}
}
Answer the question
In order to leave comments, you need to log in
You are stopping the wrong coroutine.
In the line StopCoroutine(spawn());
you create a new one, and the old one continues to work.
And maybe it happens in the update - you spawn a new car for each frame.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question