Hey all. New unity user with a quick question here.
I have a script with a small piece of code to make the player jump. The important bits:
Rigidbody2D rb; //Defining a Rigidbody2D variable
rb = GetComponent<Rigidbody2D>(); //Not sure what this does.
if (Input.GetButton("Jump") && grounded)
{
rb.AddForce(Vector2.up * jumpForce);
}
My question is why do I need to have the first two lines involving the rigidbody2d variable?
Can someone explain why I can’t just directly ‘access’ the rigidbody, instead of having to call the GetComponent function? I feel like I’m missing a critical piece of how Unity functions.
It’s just a getter method to return a reference to the Component. Not every MonoBehavior will have a Rigidbody2D, so there’s no reason to have a dedicated property for it. Every MonoBehavior has a gameObject and a transform though, which is why you can just get those by accessing them directly.
GetComponent is also pretty scalable, as it will also allow you to get components you create as well. If you wrote a script, you could call GetComponent<YourScriptName>() and it would retrieve it for you.