Unity生成预制体克隆后随机标签颜色脚本不生效问题求助
问题根因
- 核心错误是
RandomColorAndTag脚本中使用GameObject.Find()属于全局搜索场景内的同名对象,你所有克隆出来的预制体内部的子物体命名都是Cube (2)到Cube (5),所以每次搜索都会优先返回第一个生成的预制体里的对应子物体,导致只有第一个预制体被修改。 - 额外问题点:你重复实例化了多个
System.Random对象,Unity启动后短时间生成的Random实例种子相同,会导致随机结果重复;同时初始化vector时的1/3是整数除法,计算结果会为0,和预期的浮点数结果不符。
修复方案
将全局查找修改为仅查找当前预制体下的子物体,同时优化随机数实现逻辑,修改后代码如下:
修复后的RandomColorAndTag脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomColorAndTag : MonoBehaviour { int el = 0 ; void Start() { // 随机范围和原逻辑保持一致,取2-5的整数 el = Random.Range(2, 6); // 仅搜索当前脚本挂载的预制体的子物体,不会找到其他克隆对象的子物体 Transform targetCube = transform.Find($"Cube ({el})"); if(targetCube != null) { Renderer cubeRender = targetCube.GetComponent<Renderer>(); cubeRender.material.color = Color.green; targetCube.tag = "Green"; } } }
修复后的GameManager脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public GameObject firstBarrier; public GameObject secondBarrier; public int numOfBarriers = 0; Vector3 vector = new Vector3(5, 1/3f , 1); void Start() { for (numOfBarriers = 0; numOfBarriers < 10; numOfBarriers++) { int ewq = Random.Range(1, 20); int rY = Random.Range(1, 4); if(ewq <= 10) { Instantiate(firstBarrier, vector, Quaternion.identity); } else { Instantiate(secondBarrier, vector, Quaternion.identity); } vector.x -= 7; vector.y = rY; } } }
注意事项
要确保RandomColorAndTag脚本是挂载在你两个屏障预制体(firstBarrier、secondBarrier)的根节点上,这样脚本启动时搜索子物体才会正确找到当前预制体内部的Cube。
内容的提问来源于stack exchange,提问作者Gvinblyad
相关产品推荐
相关产品推荐

