How do getting a hold of componets work in unity?

I am just getting into unity but I have been using unreal engine for quite a while. I am confused by this way of getting hold of a rigid body.

Rigidbody rb;

void Start()
        rb = GetComponent<Rigidbody>();

I understand this is a way of doing it but it doesn’t make sense to me. I think that the first line is creating a varable of type Rigidbody. Then the rd = line of code I think fills it with the information the component rigid body. But then you can use this to set the velocity of the character with the rigid body component attached to it. Wouldn’t you need a pointer for this?
I just don’t understand whats going on. Does anyone know what this is really doing?

You are thinking of C# in C++ terms.
In C# we don’t really call them pointers, we call them references. They’re not quite the same, but they do pretty much the same thing. You can read about the difference here: Difference between a pointer and a reference

GetComponent gets a reference to the rigidbody. What it’s doing is taking the game object this instance of the script (component) is attached to, and looks at all the other components attached to this game object for a Rigidbody component and when it finds it, it will return a reference to it. With a reference we don’t only have the information. We can change the velocity (for instance) because we have a pointer (if you will) to the actual data

1 Like

Thank you, that was very helpful, I understand now.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms