I’m working through video #2 of the Roll-a-ball tutorial
Just wondering what the < and > brackets do in this statement: rb = GetComponent**<****Rigidbody>**();
I understand that rb is of the Unity data type Rigidbody. I understand that GetComponent() is a function / method. Is GetComponent() a function / method within the GameObject class? If so, are we calling this function without going through an object or reference? Don’t get that…
This is a C# feature called generics. Also, you are calling a method on an instance, GetComponent in this case is an instance method of the MonoBehaviour class you inherited from. That method in turn probably just calls the one on the gameObject, it’s there mostly for brevity.
Thanks for the quick response, I see that GetComponent is a method in GameObject class and it is also a method in the MonoBehavior class and also the Component class. I’m a bit confused by this but then I’m totally new to Unity and game engine programming in general.
I’m confused by what “generics” means but I’ll look it up. Thanks for pointing me in the right direction.
Generics is just a way to specify a type as part of a method or other type. So GetComponent() is technically a different function than GetComponent(). In this case it’s mostly being used as a shorthand for GetComponent(typeof(Rigidbody)), but with other uses it’s more apparent. For example a List type stores a resizable array of ints. It’s a separate type of List or List.
Hello UziMonkey, I have a doubt, is the code line rb = GetComponent(); is really required? If u consider the code I have below for debugging the velocity for my player object I didnt use the code line at all instead I simply called for the rb.velocity to get the values.
using UnityEngine;
public class playerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 500f;
public float sidewaysForce = 500f;
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
//Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);