我不能在Unity中为Vector3添加扩展方法吗?

Shi*_*iya 3 c# unity-game-engine

当我想改变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)

有什么办法吗?谢谢。

Ste*_*ler 5

尝试这个:

public static class Vector3Extensions
{
    public static Vector3 SetX(this Vector3 pos, float x)
    {
        return new Vector3(x, pos.y, pos.z);
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

Vector3 v = new Vector3(1, 2, 3);

v = v.SetX(4);
Run Code Online (Sandbox Code Playgroud)

或者,对于转换,如下所示:

transform.position = transform.position.SetX(4);
Run Code Online (Sandbox Code Playgroud)

编辑:

根据 D. Stanley 的观点,您可以通过以下方式扩展 Transform 类:

public static class TransformExtensions
{
    public static void SetXPos(this Transform t, float x)
    {
        t.position = t.position.SetX(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

transform.SetXPos(4);
Run Code Online (Sandbox Code Playgroud)