3

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 Answer 1

5

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);
3
  • 1
    +1 The key here is that you have to re-set the position property. There's no way to change an immutable property value in-place.
    – D Stanley
    Mar 10, 2020 at 17:44
  • 1
    Thank you for your quick reply. It helps me alot. I decided to use transform.SetXPos() method like you showed. thanks. Mar 10, 2020 at 18:15
  • Glad I could help. I hope you will mark my answer as correct. Cheers! Mar 10, 2020 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.