如何在运行时创建新的父子对象?



对于按钮,单击两个新游戏对象,第二个设置为第一个的子对象,第一个是附加对象的子对象。但它不起作用/显示在层次结构上,但创建的对象没有出现在游戏窗口中。

这是代码:

public void CreateTextButtonClick(string text)
{
Debug.Log("Hey starting of this..");
//Create Canvas Text and make it child of the Canvas
GameObject txtObj = new GameObject("myText");
txtObj.transform.SetParent(this.transform, false);

GameObject pan = new GameObject("text");
pan.transform.SetParent(txtObj.transform);
//Attach Text,RectTransform, an put Font to it
Text txt = pan.AddComponent<Text>();
txt.text = text;
Font arialFont = Resources.GetBuiltinResource<Font>("Arial.ttf");
txt.font = arialFont;
txt.lineSpacing = 1;
txt.color = Color.blue;

//image
//GameObject back = new GameObject("image");
//back.transform.SetParent(txtObj.transform);
//Image i = back.AddComponent<Image>();
Debug.Log("Hey its done..");
}

实现这种多层次对象制作的解决方案是什么?

您在第一个要成为画布子级的对象中正确使用了SetParent,方法是将false传递给它,从而使它保持其本地方向:

GameObject txtObj = new GameObject("myText");
txtObj.transform.SetParent(this.transform, false);

但是您没有对将成为上述对象的子对象的"文本"对象执行此操作:

GameObject pan = new GameObject("text");
pan.transform.SetParent(txtObj.transform);

还可以通过将false传递给它来解决此问题,以便 UI 组件保持其本地方向。不相关,但我也认为您也应该在父对象中添加RectTransform。将RectTransform添加到画布下的任何内容。

您的新代码:

public void CreateTextButtonClick(string text)
{
Debug.Log("Hey starting of this..");
//Create Canvas Text and make it child of the Canvas
GameObject txtObj = new GameObject("myText");
txtObj.AddComponent<RectTransform>();
txtObj.transform.SetParent(this.transform, false);
GameObject pan = new GameObject("text");
pan.transform.SetParent(txtObj.transform, false);
//Attach Text,RectTransform, an put Font to it
Text txt = pan.AddComponent<Text>();
txt.text = text;
Font arialFont = Resources.GetBuiltinResource<Font>("Arial.ttf");
txt.font = arialFont;
txt.lineSpacing = 1;
txt.color = Color.blue;
}

在您的注释代码中,看起来您也计划使用组件添加另一个子对象Image我已经在那里看到了这个错误。不要忘记这样做。否则,您将遇到问题。这适用于您计划放置在Canvas下的所有内容。

最新更新