简体   繁体   English

Unity将内容动态添加到NGUI网格

[英]Unity add content dynamicly to NGUI grid

I am using Unity 5.5.2f and NGUI 3.9.4 and I want to take advantage of NGUI's Grid to auto arrange items in perfect display. 我正在使用Unity 5.5.2f和NGUI 3.9.4,并且我想利用NGUI的网格来自动安排项目的显示效果。

The thing is that when I add items in the hierarchy manually things will work fine but when I add items through the script , Grid won't arrange my items. 问题是,当我手动在层次结构中添加项目时,一切都会很好,但是当我通过脚本添加项目时,Grid不会安排我的项目。

Here is the code that I use to add items to level board. 这是我用来将物品添加到水平板上的代码。 在此处输入图片说明

void Start () {

        List<Level> levels = ApplicationModel.Levels;
        GameObject currentWrap = null;
        Debug.LogWarning(levels.Count);
        for (int i = 0; i < levels.Count; i++)
        {
            if(i%4 == 0){

                currentWrap = Instantiate(levelWrap,transform,false);

            }
            if (levels[i].IsLock){

                GameObject go = Instantiate(levelLocked, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);

                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
            }
            else
            {

                GameObject go = Instantiate(levelActive, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);
                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
                for (int j = 0; j < levels[i].StarGet;j++){
                    go.transform.Find("fills").GetChild(j).gameObject.SetActive(true);
                }

            }
        }

    }

Ok, I find the trick, after Instantiate the wrap item, I should AddChild() to the grid system. 好的,我找到了窍门,在实例化包装项目之后,我应该将AddChild()到网格系统。

 if(i%4 == 0)
 {                  
   currentWrap = Instantiate(levelWrap,transform,false);
   GetComponent<UIGrid>().AddChild(currentWrap.transform);   
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM