3

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)?

  • 3
    Please read: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) --- Please read: [Can I ask only one question per post?](https://meta.stackexchange.com/questions/222735/can-i-ask-only-one-question-per-post) --- How is the question related to java? – Turing85 Sep 08 '22 at 18:27

1 Answers1

7

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.

David
  • 208,112
  • 36
  • 198
  • 279