首页 > 解决方案 > 如何使具有多个兄弟姐妹的新游戏对象遵循其父对象布局规则?

问题描述

附加到按钮的按钮单击功能将创建新的游戏对象,第一个将是参考游戏对象的子对象,第二个将是第一个的子对象。引用的对象附加了垂直布局组,但创建的子对象不遵循顺序。

下面是创建新对象的代码:

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


    //image
    GameObject back = new GameObject("image");
    back.transform.SetParent(txtObj.transform, false);

    Image i = back.AddComponent<Image>();

    //text
    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;

    Debug.Log("Hey its done..");

}

在这里,孩子出现在同一个地方,而预计是从上到下的顺序。

以下是未处于播放模式时的屏幕截图:

在此处输入图像描述

这是在播放模式下的屏幕截图,在单击两个按钮后,该对象出现在 scrollViews 面板上,但以意想不到的方式出现:

在此处输入图像描述

拖动它会显示对象。

并且没有子对象的对象也遵循该布局规则。


该对象如何在视口中正确显示一个又一个的顺序?


谢谢。


更新:

对于多行字符串,使用 [Soragge] 的给定代码,这将在选中高度复选框的情况下发生: 在此处输入图像描述

未选中高度复选框:

在此处输入图像描述

可以通过添加更多对象使其动态化吗?

标签: c#unity3d

解决方案


可能您的新对象缺少 RectTransform。尝试这个:

GameObject txtObj = new GameObject("myText", typeof(RectTransform));

如果您希望它们从顶部开始显示,请取消选中布局组件中的两个高度复选框。

编辑: 如果您希望内容适合文本,请选中 Height 复选框并将ContentSizeFitter组件添加到 Content 游戏对象并Vertical Fit设置为Preferred Size. txtObj还必须附加一个布局组。这应该可以解决问题:

public void CreateTextButtonClick(GameObject panel)
{
    string text = "hello..";
    Debug.Log("Hey starting of this..");

    //Create Canvas Text and make it child of the Canvas
    GameObject txtObj = new GameObject("myText", typeof(RectTransform));
    txtObj.transform.SetParent(panel.transform, false);
    HorizontalLayoutGroup layoutgroup = txtObj.AddComponent<HorizontalLayoutGroup>();
    layoutgroup.childAlignment = TextAnchor.MiddleCenter;
    layoutgroup.childControlWidth = false;

    //image
    GameObject back = new GameObject("image");
    back.transform.SetParent(txtObj.transform, false);
    back.AddComponent<LayoutElement>().ignoreLayout = true;
    Image i = back.AddComponent<Image>();
    RectTransform imageRectTransform = back.GetComponent<RectTransform>();
    imageRectTransform.anchorMin = Vector2.zero;
    imageRectTransform.anchorMax = Vector2.one;
    imageRectTransform.sizeDelta = Vector2.zero;

    //text
    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;

    Debug.Log("Hey its done..");
}

推荐阅读