Can't I add an extension method to Vector3 in Unity?

Viewed 1728

When I want to change position of a transform in Unity, I usually do as follows:

var x = 10f;
transform.position = new Vector3(x, transform.position.y, transform.position.z);

But I think this is a little tedious. So I added this extension method to a Vector3 class.

public static class Vector3Extensions
{
    public static void SetX(this Vector3 pos, float x)
    {
        pos = new Vector3(x, pos.y, pos.z);
    }
    ....

When I called that, there is no error but actually the value is not changed. Yeah I know this would be happened because Vector3 is struct. I tried to add a ref keyword to my methods,

    public static void SetX(ref this Vector3 pos, float x)
    {
        pos = new Vector3(x, pos.y, pos.z);
    }

but it doesn't work because "A property or indexer may not be passed as an out or ref parameter" error occurs. I want to do just like as:

transform.position.SetX(10f);

Is there any way? thanks.

1 Answers

Try this:

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

And use it like this:

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

v = v.SetX(4);

or, for a transform, like this:

transform.position = transform.position.SetX(4);

EDIT:

Per D. Stanley's point, you could extend the Transform class with this:

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

And call it like this:

transform.SetXPos(4);
Related