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.
atob, all you are doing is setting the pointers to the same section of memory. Therefore, if you alter the memory that they both point to, they will both have the same new value.localRigidBodyin this case will be a reference to that rigidbody, not a copy. Aside of some caching stuff etc. this can be seen as some quality of life because instead of doing something likerb.AddForceyou would otherwise always have to write something likeGameObject.FindWithTag("Foo").GetComponent<RigidBody>().AddForce().