c# - 统一错误 : Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption

标签 c# unity3d

我想动态创建 ui 按钮,

我有一个预制件,

代码如下:

  public class SFSConnect : MonoBehaviour {
        SmartFox sfs;

        public GameObject cnv1;
        public GameObject potchPrf;
        public Canvas fCanvas;
    void Start () {
    fCanvas = cnv1.GetComponent<Canvas> ();

            Button ptf1 = potchPrf.GetComponent<Button> ();

            Instantiate(ptf1,new Vector3 (0, 0, 10), Quaternion.identity);


            potchPrf.transform.SetParent (fCanvas.transform);
    }

}

我尝试了数千个帖子,但没有任何反应

最佳答案

问题可能来自 potchPrf.transform.SetParent (fCanvas.transform);,这意味着您正在尝试修改预制件。您无法通过代码更改预制件的父级。

也许您想设置实例化对象的父对象?

如果是这种情况,则将其存储在变量中

GameObject uiObj = Instantiate<GameObject>(ptf1,new Vector3 (0, 0, 10), Quaternion.identity);
uiObj.transform.SetParent (fCanvas.transform);

另外,不要试图让预制件成为 GameObject 的父级。你遇到了 this问题。您要设置为父游戏对象和目标(子)游戏对象都不应是预制件。


如果您的 UI 不复杂,我会完全避免这样做,而只是使用 DefaultControls 动态创建 UI。参见 this发布了很多关于如何使用 DefaultControls 创建 UI 控件的示例。

关于c# - 统一错误 : Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46063784/

相关文章:

c# - 将 Launch10=shell.exe 更改为另一个值...现在怎么办?

user-interface - 世界空间中的 UI 文本显示

c# - Visual Studio : c# interactive shell window

c# - Newtonsoft Json反序列化: How to throw an error if/when the given json string has MORE properties than necessary?

c# - WinForms 禁用双击并接受所有鼠标点击?

c# - 存在从 'float' 和 'float' 以及从 'float' 到 'float' 的隐式转换

ios - 如何使用第三方应用程序在 iPad 上实现分屏多任务处理?

c# - 自动按下 iframe 中的按钮

unity3d - UI 上 Unity 粒子系统中的渲染问题

c# - 完全空白 Unity/Microsoft Store Build 未通过 WACK 测试