0
votes

I have a problem, I have three scenes in my game, shop, main menu, and game. In game I have a script that spawns enemies every second. So my problem is if I wait 20 seconds in the main menu or shop, and go to the game, it will spawn 20 enemies at one time(script is in the empty game object), I tried a lot of fixes. That is my latest spawn enemy script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SpawnScript : MonoBehaviour
{
    public Transform[] spawnPoints;

    public GameObject[] enemyPrefabs;

    public float nextActionTime;

    public float period;

    private bool startScript = false;
    void Start()
    {
        Scene currentScene = SceneManager.GetActiveScene();

        string sceneName = currentScene.name;

        if (sceneName == "Game")
        {
            nextActionTime = 0.0f;
            period = 1f;
            startScript = true;
        }
    }
    void Update()
    {
        if (startScript != false)
        {
            if (Player.isDead != true)
            {
                if (Time.time > nextActionTime)
                {
                    nextActionTime += period;
                    int spawnArrayKey = Random.Range(0, 4);
                    int enemyId = Random.Range(0, 3);
                    Instantiate(enemyPrefabs[enemyId], spawnPoints[spawnArrayKey].position, spawnPoints[spawnArrayKey].rotation);
                }
            }
        }
    }
}

I also tried to change void Start() to void Awake(), still don't work, here is the main menu script which is very simple

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Buttons : MonoBehaviour
{
    public void PlayGame()
    {
        SceneManager.LoadScene("Game");
    }
    public void GoToShop()
    {
        SceneManager.LoadScene("Shop");
    }
}

Also here is my build manager enter image description here

1
Its not unfixable. Perhaps when you come back from a menu or whatever you need to reset the next action timeBugFinder

1 Answers

3
votes

I found answer, I had Time.time at my script, I have set it to Time.timeSinceLevelLoad And now it works