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());
    }
}
缺点是。。多了个字典


猜你喜欢

转载自blog.csdn.net/qq_17813937/article/details/79543944