Greetings everyone. Im very new to unity and to programming, so whats im doing now isnt about “making a game”, its more about learning. Currently im trying to make a RTS-like controls and stuff - so far i made cam movement, nav mesh movement with blending animations, selection system on camera and stat system in “units”. And i found myself wondering a question (which is probably reeeeeeealy sillly) :
Is GetComponent a “snapshot”-like or “reference”-like? What do i mean - if in some script i used GetComponent to get a stats from one gameobject and changed them will they change in gameobject`s script?
In most programming languages, there are two ways to “get” something: by value, and by reference.
Get by value is done for things like primitive types (integers, floats, booleans) and structs (Unity’s Vector3 and Color). So when you get the value of something and change it, you’re changing that value and not the original. Example:
int x = 5;
int y = x;
y += 5;
// x = 5, y = 10
Get by reference is performed on classes, where assigning a variable the value of another variable makes them both reference the same object.
Person awesomeGuy = new Person("Schneider21");
awesomeGuy.age = 33;
Person coolDude = awesomeGuy;
coolDude.age += 1;
// awesomeGuy.age = 34, coolDude.age = 34
Unity’s MonoBehavior class (also referred to as Components) is handled just like any other class in this regard. So calling GetComponent() returns a reference to that object. If you think about it, it’d be sorta useless to have it work the other way around, where it created a new clone, right?
Thanks, that`s exactly what i was wondering about.