0

I was trying to write a utility function that will change the Vector3 's x value so I can only write

transform.position.SetVectorX(newX);

instead of:

Vector3 temp = new Vector3(newx, transform.position.y, transform.position.z);
transform.position = temp;

So I tried this but I don't understand why it does not work:

namespace MyUtility
{
    public static class Extension
    {
        public static Vector3 SetVectorX(this Vector3 v, float x)
        {
            return v = new Vector3(x, v.y, v.z);
        }

    }
}

1 Answers1

1

You need to think one level higher. You can write an extension method for the Transform that sets its position.

public static class Extension
{
    public static void SetPositionX(this Transform t, float x)
    {
        var v = t.Position;
        t.Position = new Vector3(x, v.y, v.z);
    }
}

Call it like this:

transform.SetPositionX(newX);

As for your original idea, see this question.

John Wu
  • 50,556
  • 8
  • 44
  • 80