1

Is there a way to change the Unity Vector3 struct value inside an Extension Method in this way?

Vector3 myVector = new Vector(3.5f, 0.7f, 2f);
myVector.Floor(); // it should be (3f, 0f, 2f) instead it's (3.5f, 0.7f, 2f) still

it only works in this way:

myVector = myVector.Floor(); // now it's (3f, 0f, 2f) 

Extension Code:

public static void Floor(this Vector3 vector)
{
    vector.Set(Mathf.Floor(vector.x), Mathf.Floor(vector.y), Mathf.Floor(vector.z));
}

or

public static void Floor(this Vector3 vector)
{
    vector.x = Mathf.Floor(vector.x);
    vector.y = Mathf.Floor(vector.y);
    vector.z = Mathf.Floor(vector.z);
}
ProtoTyPus
  • 1,272
  • 3
  • 19
  • 40
  • Vector3 seems to be a struct have a look at: https://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net – Rand Random Oct 02 '22 at 14:50

1 Answers1

6

Your extension method should be like this:

public static void Floor(ref this Vector3 vector)
{
    vector.x = Mathf.Floor(vector.x);
    vector.y = Mathf.Floor(vector.y);
    vector.z = Mathf.Floor(vector.z);
}

because struct is value type

Here's an example: https://dotnetfiddle.net/NItg0O

ggeorge
  • 1,496
  • 2
  • 13
  • 19