脚本生成的GameObject Transform属性无法修改?原因及解决办法
问题解决思路
一、普通GameObject的Transform修改问题
你当前的代码在设置父物体后直接修改世界坐标/旋转,会因为父物体的变换层级导致设置被覆盖。可以通过两种方式修正:
方案1:使用SetParent重载方法保留世界空间属性
private void AddObj(Transform Grandparent) { int n = 2; foreach (Transform Parent in Grandparent) { foreach (Transform child in Parent) { GameObject obj = new("obj-" + n++); obj.AddComponent<Rigidbody>(); // 第二个参数设为false,保持当前物体的世界空间属性不变 obj.transform.SetParent(child, false); } } }
方案2:先设父物体,再使用局部空间属性
private void AddObj(Transform Grandparent) { int n = 2; foreach (Transform Parent in Grandparent) { foreach (Transform child in Parent) { GameObject obj = new("obj-" + n++); obj.AddComponent<Rigidbody>(); obj.transform.parent = child; // 使用局部坐标、旋转、缩放,而非世界空间属性 obj.transform.localPosition = Vector3.zero; obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = child.localScale; } } }
另外Awake中的代码可以简化为:
GameObject obj= new("obj-1"); obj.AddComponent<Rigidbody>(); obj.transform.SetParent(transform, false); // 或者直接复制当前物体的变换参数 obj.transform.CopyFrom(transform);
二、UI Text的RectTransform修改问题
UI元素的RectTransform和普通Transform逻辑完全不同,你的问题核心是属性使用时机和类型错误,修正后的代码如下:
public Canvas canvas; public Transform panel; private void Start() { List<string> props = MCP.GetPropertiesNames(); RectTransform panelRect = panel.GetComponent<RectTransform>(); float itemWidth = panelRect.sizeDelta.x / props.Count; for (int n = 0; n < props.Count; n++) { // 直接创建带Text组件的对象,自动生成RectTransform GameObject textObj = new GameObject("Property-" + (n + 1), typeof(Text)); RectTransform rect = textObj.GetComponent<RectTransform>(); // 设置父物体,UI场景下一般设为true,继承父物体的UI缩放 rect.SetParent(panel, true); // 初始化基础变换属性 rect.localRotation = Quaternion.identity; rect.localScale = Vector3.one; // 设置锚点和 pivot rect.anchorMin = new Vector2((float)n / props.Count, 1); rect.anchorMax = new Vector2((float)n / props.Count, 1); rect.pivot = new Vector2(0, 1); // 设置尺寸和锚点偏移(UI专用属性) rect.sizeDelta = new Vector2(itemWidth, 50); rect.anchoredPosition = Vector2.zero; // 设置Text内容与基础样式 Text text = textObj.GetComponent<Text>(); text.text = props[n]; // 必须指定字体,否则运行时看不到文字 text.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); text.color = Color.black; } }
关键注意点:
- UI元素必须使用
RectTransform的专属属性:anchoredPosition控制位置、sizeDelta控制尺寸,不要用普通Transform的position; - 创建UI对象时直接指定
typeof(Text),避免后续从Transform转RectTransform导致的属性丢失; - Text组件必须指定字体,否则运行时无法显示文字。
内容的提问来源于stack exchange,提问作者Eagle32349
相关产品推荐
相关产品推荐

