I need some help with understanding variable assignment with the C# language.
While scripting with Monodevelop for Unity, I assign RigidBody and Collider components (among others) of game objects to local variables. When I change those variables, either by calling their methods or changing their attributes, those changes are reflected in the original components. To make my point clearer I'll leave this pseudo-code below:
void someMethod(Rigidbody rb)
{
Rigidbody localRigidBody;
localRigidBody = rb; //assigned external rb component to local rigidBody
localRigidBody.velocity = 10.0f; //changes are reflected in the original rb object!
}
What confuses me are the changes in the game object which "contains" the rb Rigibody component. While I know this works, in mind it shouldn't work, because localRigidBody is a local variable, and changing the velocity of localRigidBody shouldn't change the velocity value of rb. Yet it changes, and it works, as the object with the rb component changes its velocity when i run my program. Can you explain me why?
Please inform me if my question isn't clarified and I'll try to express myself better.
Thank you.
Unity is passing that Rigidbody
by reference. If you want a copy
or clone
of Rigidbody
that is totally independent of the original object (rb
) that was passed to your method you can use Instantiate
:
void someMethod(Rigidbody rb)
{
Rigidbody localRigidBody = Instantiate<Rigidbody>(rb);
localRigidBody.velocity = 10.0f;
}
Otherwise in your original, as @RB stated, your localRigidBody
is just an "alias" to the original rb variable as they both point to the same object (memory location).
See this SO question/answer to understand what passing by "reference" is: Passing Objects By Reference or Value in C#
Update:
What if I create a simple script where I declare a variable "int a = 10;" and then "int b = a" followed by "b=8". Will "a" change its value? Or is "b" an alias also?
Primitive data types are handled a little differently ;-) I would advice do some research on primitive vs. reference types, Microsoft has some great articles concerning this... your example:
Code:
int a = 10;
Console.WriteLine (a);
int b = a;
Console.WriteLine (b);
b = 8;
Console.WriteLine (a);
Console.WriteLine (b);
Output:
10
10
10
8
Press any key to continue...