给Unity的GameObject拓展接口

本文介绍了一个Unity的扩展方法,该方法提供了一种便捷的方式来获取或添加GameObject上的组件。通过使用GetOrAddComponent泛型方法,可以简化游戏开发中组件管理的工作流程。

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

现在,我们想给GameObject拓展一些接口,我们知道GameObject有AddComponent和GetComponent接口

我们如何给GameObject拓展一个GetOrAddComponent接口呢?

代码如下:

using UnityEngine;

//Unity的一些扩展方法
static public class MethodExtensionForUnity
{
    /// <summary>
    /// Gets or add a component. Usage example:
    /// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
    /// </summary>
    static public T GetOrAddComponent<T>(this Component child, bool set_enable = false) where T : Component
    {
        T result = child.GetComponent<T>();
        if (result == null)
        {
            result = child.gameObject.AddComponent<T>();
        }
        var bcomp = result as Behaviour;
        if (set_enable)
        {
            if (bcomp != null) bcomp.enabled = true;
        }
        return result;
    }

    static public T GetOrAddComponent<T>(this GameObject go) where T : Component
    {
        T result = go.transform.GetComponent<T>();
        if (result == null)
        {
            result = go.AddComponent<T>();
        }
        var bcomp = result as Behaviour;
        if (bcomp != null) bcomp.enabled = true;
        return result;
    }


    public static void walk(this GameObject o, System.Action<GameObject> f)
    {
        f(o);

        int numChildren = o.transform.childCount;

        for (int i = 0; i < numChildren; ++i)
        {
            walk(o.transform.GetChild(i).gameObject, f);
        }
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林新发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值