You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何启用该脚本后Unity卡在Application.EnterPlayMode?

问题原因及解决方案

核心问题

你的脚本直接导致Unity卡死的原因有两个:

  • 主线程被强制阻塞:Thread.Sleep(1000)在Unity主线程中执行,会让整个游戏进程暂停响应——Unity的所有核心逻辑(包括进入Play Mode的初始化、帧渲染、输入处理)都在主线程运行,一旦主线程被Sleep卡住,程序就彻底失去响应,只能通过任务管理器终止。
  • 无限递归调用:Timer()函数最后又调用了自身,形成了无限递归。即使Sleep的问题解决,这种写法也会不断消耗栈内存,最终引发栈溢出错误。

正确实现方式

Unity中实现定时逻辑,应该用协程(Coroutine)或者Update帧计时,这两种方式都不会阻塞主线程:

方式1:协程实现(推荐)

using System.Collections;
using UnityEngine;

public class EnemySpawnerScript : MonoBehaviour
{
    public GameObject enemyPrefab;
    public int spawnRate = 5;
    private System.Random random;

    void Start()
    {
        random = new System.Random();
        StartCoroutine(SpawnEnemyCoroutine());
    }

    IEnumerator SpawnEnemyCoroutine()
    {
        while (true)
        {
            // 等待指定秒数,不会阻塞主线程
            yield return new WaitForSeconds(spawnRate);
            
            int randomYPos = random.Next(0, 5);
            SpawnNewEnemy(randomYPos);
        }
    }

    void SpawnNewEnemy(float yPos)
    {
        Instantiate(enemyPrefab, new Vector2(-12, yPos), Quaternion.identity);
    }
}

方式2:Update帧计时

using UnityEngine;

public class EnemySpawnerScript : MonoBehaviour
{
    public GameObject enemyPrefab;
    public int spawnRate = 5;
    private float timer = 0;
    private System.Random random;

    void Start()
    {
        random = new System.Random();
    }

    void Update()
    {
        timer += Time.deltaTime;
        if (timer >= spawnRate)
        {
            timer = 0;
            int randomYPos = random.Next(0, 5);
            SpawnNewEnemy(randomYPos);
        }
    }

    void SpawnNewEnemy(float yPos)
    {
        Instantiate(enemyPrefab, new Vector2(-12, yPos), Quaternion.identity);
    }
}

额外优化点

  • 不要每次生成敌人都新建System.Random实例,应该在Start中初始化一次,避免因时间戳相近导致生成的随机数重复。

内容的提问来源于stack exchange,提问作者Ninju4821

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:27:28