Unity点击Play后无限等待,提示Application.EnterPlayMode等待代码执行求助
Unity进入Play模式无限等待问题修复
问题现象
点击Play按钮后,Unity无限等待场景启动,Hold On窗口提示:Application.EnterPlayMode Waiting for Unity's code to finish executing。项目为URP场景,仅包含全局体积、平行光和一个挂载了以下脚本的平面:
using UnityEngine; public class PerlinNoise : MonoBehaviour { [Header("Resolution")] [Space] public int width = 256; public int heigth = 256; [Space] [Header("Adjustments")] [Space] public float scale = 20; public float xOffset = 10; public float yOffset = 10; void Update() { Renderer renderer = GetComponent<Renderer>(); renderer.material.mainTexture = GenerateTexture(); } Texture2D GenerateTexture() { Texture2D texture = new Texture2D(width, heigth); for (int x = 0; x < width; x++) { for (int y = 0; x < heigth; y++) { Color color = GenerateColor(x, y); texture.SetPixel(width, heigth, color); } } texture.Apply(); return texture; } Color GenerateColor(int x, int y) { float xCoord = (float)x / width * scale + xOffset; float yCoord = (float)y / width * scale + yOffset; float perlinNoise = Mathf.PerlinNoise(xCoord, yCoord); return new Color(perlinNoise, perlinNoise, perlinNoise); } }
问题根源
脚本中的GenerateTexture方法存在死循环:内层for循环的终止条件错误地写成了x < heigth,而非y < heigth。当进入Play模式时,Update方法立即执行并调用GenerateTexture,内层循环会无限执行(y持续自增但循环条件始终成立),导致Unity主线程被阻塞,无法完成Play模式启动流程。
此外脚本还存在两个次要问题,虽不会导致卡死,但会影响纹理生成效果:
- 变量名
heigth拼写错误(正确应为height) texture.SetPixel(width, heigth, color)参数错误,应传入当前循环的x和y坐标,而非纹理的宽高值
修复步骤
- 打开
PerlinNoise脚本,定位到GenerateTexture方法的内层for循环 - 将循环条件
x < heigth修改为y < heigth - (可选但建议)修正变量名拼写错误,将所有
heigth替换为height - (可选但建议)修正
SetPixel的参数为texture.SetPixel(x, y, color)
修正后的完整代码
using UnityEngine; public class PerlinNoise : MonoBehaviour { [Header("Resolution")] [Space] public int width = 256; public int height = 256; [Space] [Header("Adjustments")] [Space] public float scale = 20; public float xOffset = 10; public float yOffset = 10; void Update() { Renderer renderer = GetComponent<Renderer>(); renderer.material.mainTexture = GenerateTexture(); } Texture2D GenerateTexture() { Texture2D texture = new Texture2D(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Color color = GenerateColor(x, y); texture.SetPixel(x, y, color); } } texture.Apply(); return texture; } Color GenerateColor(int x, int y) { float xCoord = (float)x / width * scale + xOffset; float yCoord = (float)y / width * scale + yOffset; float perlinNoise = Mathf.PerlinNoise(xCoord, yCoord); return new Color(perlinNoise, perlinNoise, perlinNoise); } }
- 保存脚本后,重新点击Play按钮,即可正常进入场景。
内容的提问来源于stack exchange,提问作者Gabriele
相关产品推荐
相关产品推荐

