I
I
igorloadgame2021-02-16 11:03:59
C++ / C#
igorloadgame, 2021-02-16 11:03:59

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

1 answer(s)
V
Vasily Bannikov, 2021-02-16
@igorloadgame

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 question

Ask a Question

731 491 924 answers to any question