Unity 扩展办法,扩展字段

C# 在3.5后增加了扩展方法概念,它看起来是这样的

必须在静态类内才能扩展,方法必须是静态方法。

必须使用 this 关键字对第一个参数修饰

public static class Extend
{
	public static T SetName<T>(this T behaviour, string name)where T:MonoBehaviour
    {
        behaviour.gameObject.name = name;
        return behaviour;
    }
}

假如扩展的方法只有泛型没有实际参数时


你需要指定this为非泛型

public static class Extend
{
    public static T2 AddComponent<T2>(this MonoBehaviour behaviour)  where T2 : Component
    {
        return behaviour.gameObject.AddComponent<T2>();
    }
}

public class Test : MonoBehaviour
{
    private void Awake()
    {
        this.AddComponent<CanvasGroup>();
    }
}



如果你想要对旧的类添加字段,但该添加的字段和旧的类的并没有什么关联

public class Test : MonoBehaviour
{
    private void Awake()
    {
        this.AwakeExtend();
    }

    private void OnDestroy()
    {
        this.DestroyExtend();
    }
}

public static class TestExtend
{
    static Dictionary<Test, int> m_SpeedDic = new Dictionary<Test, int>();
    public static void AwakeExtend(this Test test)
    {
        m_SpeedDic[test] = 0;
    }

    public static void DestroyExtend(this Test test)
    {
        m_SpeedDic.Remove(test);
    }
    
    public static void SetSpeed(this Test test, int speed)
    {
        m_SpeedDic[test] = speed;
    }
    public static int GetSpeed(this Test test)
    {
        return m_SpeedDic[test];
    }
}

public class Test2:MonoBehaviour
{
    private void Awake()
    {
        Test test = new GameObject().AddComponent<Test>();
        test.SetSpeed(123);
        Debug.Log(test.GetSpeed());
    }
}
缺点是。。多了个字典


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小鱼游戏开发

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

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

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

打赏作者

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

抵扣说明:

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

余额充值