C# 自定义拓展方法(this修饰符)

创建拓展方法需要创建一个静态类, 并且拓展方法也是静态, 同时第一个参数作为所操作的类型, 需要添加this修饰符

public static class Extensions
{
    //Function must be static
    //First parameter has "this" in front of type
    public static void SetPositionX(this Transform t, float newX)
    {
        t.position = new Vector3(newX, t.position.y, t.position.z);
    }
}

 

然后就可以在其他脚本里调用该拓展方法, 只修改transform.position.x属性

public class Player : MonoBehaviour   
{  
    void Update ()   
    {  
        //Set new x position to 5  
        transform.SetPositionX(5f);  
    }  
}

 

posted on 2015-10-08 15:08  黑白熊1989  阅读(314)  评论(0编辑  收藏  举报

导航