目的:
向现有类中添加方法,而无需创建派生类型、重新编译或者以其他方式修改原始类。
我们创建一个GameObject并绑定一个脚本,我们如果想修改这个物体的位置,我们可以:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangePos : MonoBehaviour
{
Transform mytrans;
void Start()
{
mytrans = this.transform;
mytrans.position = new Vector(20,0,0);
}
}
但是这样很麻烦,我们需要写XYZ三个参数。为了提高效率,我们可以可以使用扩展方法:
新建一个public类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class MyExtension
{
public static void SetPosX(this Transform trans, float X)
{
trans.position = new Vector3(X, trans.position.y, trans.position.z);
}
public static void SetPosY(this Transform trans, float Y)
{
trans.position = new Vector3(trans.position.x, Y, trans.position.z);
}
public static void SetPosZ(this Transform trans, float Z)
{
trans.position = new Vector3(trans.position.x, trans.position.y, Z);
}
}
这个扩展方法在静态类中声明,定义一个静态方法,其中第一个参数this定义可它的扩展类型。这是C#的语法特性,可以给this后面的类添加新的成员函数,即SetPosX,SetPosY,SetPosZ
之后我们就可以在ChangePos 脚本中
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangePos : MonoBehaviour
{
Transform mytrans;
void Start()
{
mytrans = this.transform;
mytrans.SetPosX(50);
}
}