Home > Software design >  C# Extension method change current value
C# Extension method change current value

Time:10-03

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);
}

CodePudding user response:

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

  • Related