当我想改变Unity中变换的位置时,我通常这样做:
var x = 10f;
transform.position = new Vector3(x, transform.position.y, transform.position.z);
Run Code Online (Sandbox Code Playgroud)
但我认为这有点乏味。所以我将此扩展方法添加到 Vector3 类中。
public static class Vector3Extensions
{
public static void SetX(this Vector3 pos, float x)
{
pos = new Vector3(x, pos.y, pos.z);
}
....
Run Code Online (Sandbox Code Playgroud)
当我调用它时,没有错误,但实际上值没有改变。是的,我知道会发生这种情况,因为 Vector3 是结构体。我尝试在我的方法中添加 ref 关键字,
public static void SetX(ref this Vector3 pos, float x)
{
pos = new Vector3(x, pos.y, pos.z);
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,因为出现“属性或索引器可能无法作为 out 或 ref 参数传递”错误。我想做的就像:
transform.position.SetX(10f);
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?谢谢。