Object.Destroy慎用

Object.Destory

Destory(Object)并没有立刻,马上,及时的删除这个Object。

举例

在使用NGUI的Table或Grid进行布局时,就需要注意了:尽量不要使用Destroy 来销毁GameObject,而是使用gameObject.SetActive(false);

image

建议方法

建议使用setactive(false)替代destory

int max = parent.childCount;
//全部都隐藏
for (int i = 0; i < max; i++)
{
    parent.GetChild(i).gameObject.SetActive(false);
}
int idx = 0;
//根据需要显示,并设置值
foreach (CWeaponVo weaponVo in weapons)
{
    UILabel atkLabel;
    var nature = weaponVo.Info.Nature.ToLower();
    
    if (!propertyLabels.TryGetValue(nature, out atkLabel))
    {
        newObj = parent.GetChild(idx).gameObject;
        newObj.SetActive(true);
        sprite = newObj.GetComponent<UISprite>();
        sprite.spriteName = iconWpProperty[nature];
        atkLabel = GetControl<UILabel>("TotalLabel", newObj.transform);
        propertyLabels[nature] = atkLabel;
    }
    idx++;
}

慎用Destory

//每次Refresh时都销毁之前的
void Refresh()
{
    foreach (var obj in PropertyObjList)
    {
        Destroy(obj);
    }
    PropertyObjList.Clear();
}
void RenderUI()
{
    foreach (CWeaponVo weaponVo in weapons)
    {
        UILabel atkLabel;
        var nature = weaponVo.Info.Nature.ToLower();

        //生成新的    
        if (!propertyLabels.TryGetValue(nature, out atkLabel))
        {
            newObj = Instantiate(properTemplate) as GameObject;
            CBase.Assert(newObj);
            newObj.SetActive(true);
            CTool.SetChild(newObj, parent.gameObject);
            sprite = newObj.GetComponent<UISprite>();
            sprite.spriteName = iconWpProperty[nature];
            atkLabel = GetControl<UILabel>("TotalLabel", newObj.transform);
            propertyLabels[nature] = atkLabel;
            PropertyObjList.Add(newObj);
        }
    }
    //重设Table位置
    properTable.Reposition();
}

意外后果

使用Destory(obj),在重设Table的位置时,因为Destory不及时 所以残留着之前的child悲伤

Instance GameObject

Instance NGUI widget

在Instance 绑有ngui组件的prefab时,建议把gameobject.setActive(false)之后再instance。不然很容易引起多生成一个UICamera。

NGUI版本:3.6.x

生成多的UICamera?

因为ngui的panel在渲染时,会检查组件是否在UICamera下,instance生成的临时对像没有ParentRoot,很容易引起bug。

 

文档资料

文档:http://game.ceeger.com/Script/Object/Object.Destroy.html

原文地址:https://www.cnblogs.com/zhaoqingqing/p/4104955.html