Object.Destroy慎用

本文探讨了在Unity结合NGUI框架时,如何更有效地管理UI元素。建议避免使用Object.Destroy来销毁GameObject,而应采用SetActive(false)方法,并提供实例说明。此外,还讨论了使用Instantiate创建带有NGUI组件的游戏对象时可能遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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


本文转自赵青青博客园博客,原文链接:http://www.cnblogs.com/zhaoqingqing/p/4104955.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值