Home > Mobile >  Although I can change properties of my custom object in methods, I cannot change properties of Vecto
Although I can change properties of my custom object in methods, I cannot change properties of Vecto

Time:09-10

I am a Java developer, Java is pass-by-value but we change change properties of an object in method. I cannot explain it well but here is a link: If Java is pass-by-value, then why can we change the properties of objects in methods? I am also developing games in Unity with C#. I wonder that the above situation can also be valid in C# language. I tried it and yes, it is valid and it is same. While trying, I defined a class myself and tried to change its property. After that, I tried with Vector3 and it did not work.

void Start()
{
    Vector3 v = new Vector3(0,0,0);
    setVector3(v);
    Debug.Log(v);
}

void setVector3(Vector3 v)
{
    v.x = 5;
}

Although we can change properties of an object in methods in C#, why cannot I change x property of Vector3 (x property can be setted like that, it is not the problem)?

CodePudding user response:

Because Vector3 is a struct, not a class. Which makes it a value-type (as opposed to a reference-type). Similar to an int for example.

So in your setVector3 method you are modifying a copy of the Vector3 object local only to that method.

You can explicitly pass it by reference:

void setVector3(ref Vector3 v)

This would tell the compiler to use the same instance of the value-type in the method frame as it used in the calling frame.

If you passed in a reference-type (something defined as a class) then you would observe by default the behavior you are expecting. That object would exist on the heap and would be the same object reference throughout the stack.

  • Related