I Just started trying to code in unity C# since I can’t afford a license for GameMaker.
And I can’t for the life of me understand how I refer to variables in other instances. From what I could find in the documentation GetComponent is the thing I’m looking for. I used it in the Roll a ball tutorial but can’t wrap my head around it
Code:
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
rb = GetComponent();
}
}
It seems to me like either the “private Rigidbody rb;” or “rb = GetComponent();” line would be unnecessary. Why would I say the pretend variable “rb” is “RigidBody” and then say the pretend variable “rb” is “RigidBody” again. Or did I miss an important memo?
And how the hell do I tell it to get a variable from another object?
This line:
private Rigidbody rb;
declares a variables of type Rigidbody. The Rigidbody type is a class and therefore a reference type. So “rb” is a variable that can hold a reference to a Rigidbody instance. However by default reference type variables have their default value which is null.
The line:
rb = GetComponent<Rigidbody>();
is actually
rb = this.GetComponent<Rigidbody>();
GetComponent will search for a Rigidbody component instance on the same gameobject your script is attached to and return the reference if such a component was found or it will return null if there isn’t such a component on this gameobject.
So the GetComponent line actually initializes the variable so it actually references the rigidbody component of this object.
Your last question is a bit vague. GameObjects do not have variables (well they have but only the name, layer, tag and some other common things). The variables you most likely talk about are variables of certain components which might be attached to a GameObject. When you create a MonoBehaviour script you actually create a new type of component. If you want to access a variable of another script or component you have to have a reference to that component instance. You get a reference by using GetComponent or by assigning the reference in the inspector.
When you declare a variable as public variable or if you use the [SerializeField]
attribute the variable will be serialized in the Unity editor and will show up in the inspector. You can simply drag and drop other gameobjects onto that variable in the inspector to assign and store the reference to that other object. If you assigned a reference through the inspector you don’t have to / shouldn’t use GetComponent to initialize the variable as this is automatically done from the serialized data when the scene loads.