带有统一时间和场景管理器的 Unity Bug

时间:2021-02-11 20:39:23

标签: c# unity3d

我有一个问题,我的游戏中有三个场景,商店、主菜单和游戏。在游戏中,我有一个每秒产生敌人的脚本。所以我的问题是如果我在主菜单或商店中等待 20 秒,然后进入游戏,它会一次产生 20 个敌人(脚本在空的游戏对象中),我尝试了很多修复。这是我最新的生成敌人脚本:

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);
                }
            }
        }
    }
}

我也试过把void Start()改成void Awake(),还是不行,这里是主菜单脚本,很简单

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");
    }
}

还有我的构建经理 enter image description here

1 个答案:

答案 0 :(得分:2)

我找到了答案,我的脚本中有 Time.time,我已将其设置为 Time.timeSinceLevelLoad 现在它可以工作了