Unity 2021.3.15f1障碍物生成脚本Build运行失效问题求助
Unity 2021.3.15f1 2D项目打包Windows后ObstacleSpawner脚本失效问题
问题描述
在Unity 2021.3.15f1版本的2D项目中,用于生成玩家跳跃障碍物的ObstacleSpawner脚本在编辑器内运行无bug,但打包到Windows平台后完全不生效。
脚本代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObstacleSpawner : MonoBehaviour { public GameObject tree; public GameObject cannonbob; public GameObject snail; public int cooldown = 2500; public int spawnOffset = 10; public bool doSpawn = true; private int cooldownIndex = 0; //How far through the cooldown it is. private GameObject player; private bool mustSpawn = false; // Start is called before the first frame update void Start() { player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update() { if(player.GetComponent<PlayerScript>().isDead == false && player.GetComponent<PlayerScript>().won == false && player.GetComponent<PlayerScript>().stopSpawning == false){ if(cooldownIndex < cooldown) { cooldownIndex += 1; } else { cooldownIndex = 1; // Note minInclusive & maxExclusive when using random range if(mustSpawn == true){ SpawnObstacle(); mustSpawn = false; } else { if(Random.Range(0,2) == 1) { SpawnObstacle(); } else { cooldownIndex = 2000; mustSpawn = true; } } } } } void SpawnObstacle(){ if(doSpawn==true){ var position = new Vector3(player.transform.position.x + spawnOffset, -2.13f, 0); int randNo = Random.Range(0,3); if(randNo == 0){ Instantiate(tree, position, Quaternion.identity); } else if(randNo == 1){ Instantiate(cannonbob, position, Quaternion.identity); } else { Instantiate(snail, position, Quaternion.identity); } } } }
已排查情况
- 脚本挂载在场景中的空GameObject上;
- 打包时曾出现警告“Unable to find player assembly: C:...\UnityProdjects\TomatoGuy\Temp\StagingArea\Data\Managed\UnityEngine.TestRunner.dll”,已通过取消勾选“Enable burst compilation”解决,但脚本失效问题仍存在;
- 不清楚如何调试Build版本,找不到Build日志文件,重启编辑器后问题依旧;
- 有视频展示编辑器正常运行、Build后脚本完全不工作的现象。
解决思路
- 优化Player对象获取逻辑:
GameObject.FindGameObjectWithTag("Player")在打包后可能因场景加载顺序或对象激活时机问题失效,建议改为在Inspector面板直接拖拽赋值Player对象,或者用FindObjectOfType<PlayerScript>()获取组件并关联对象,避免动态查找的不确定性。 - 验证随机数生成:打包后Unity的随机数种子可能固定,导致逻辑分支未触发,可在
Start()方法中添加Random.InitState((int)System.DateTime.Now.Ticks)初始化随机数种子,确保随机逻辑正常执行。 - 开启Build调试模式:打包时勾选Development Build和Script Debugging选项,运行Build程序后,在Unity编辑器中通过
Window > General > Console查看远程日志;也可在关键逻辑点添加Debug.Log()输出(比如Start中打印player是否为空、Update中打印条件判断结果、SpawnObstacle中打印是否执行),排查哪一步逻辑未触发。 - 检查脚本与资源打包状态:确保ObstacleSpawner脚本未被标记为Editor Only;检查PlayerScript中的
isDead、won、stopSpawning字段是否为public或带有[SerializeField]属性,避免打包后无法访问;确认tree、cannonbob、snail三个预制体已正确赋值,且所在场景已添加到Build Settings的Scenes In Build列表中,确保资源被正确打包。 - 查看Build日志:Unity的Build日志默认路径为
C:\Users\<你的用户名>\AppData\Local\Unity\Editor\Editor.log,或在打包完成后点击编辑器右上角的Open Editor Log按钮,查看是否有脚本编译错误、资源缺失等问题。
内容的提问来源于stack exchange,提问作者MrCPlusPlus
相关产品推荐
相关产品推荐

