What is ' RequireComponent (typeof (Waypoint)) ' all about?

Woao - Slow down a bit. Perhaps it was covered in a different course, but I don’t recall seeing
"[RequireComponent(typeof(Waypoint))]" before now. Why is this necessary?Doesn’t GetComponent<> do the trick on its own? Could you detail a little more about this, so those of us seeing this for the first time can better understand its correct usage.

Also why was “gridPos” defined in the Waypoint script - is it used somewhere later, or perhaps referenced in a different script? Or was it merely part of the creative process, but was ultimately not required?

Finally, adding to that mentioned in a separate post, usage of “new” still eludes me. In this case I am referring to it’s use in “return new Vector2D” in the Waypoint script. I Can’t explain why I am not getting it - it is currently my Achilles heel, especially since it has cropped up numerous times, and I still don’t get it.

You can use both RequireComponent and GetComponent in the same script, for the same ‘other’ item.

Let’s say we have 2 components, A and B.

A is dependent on and needs to communicate with B.

Importantly - A doesn’t work without a B present.

Then saying RequireComponent(typoof(B)) in A ensures that whenever you put A on your game object, a B will automatically be added if it’s not already on it and doesn’t have to be added separately to stop errors happening.

But that just ensures both are on your game object. If you actually want A to call methods on B, you’ll still want to GetComponent<B> in A so that you can reach out to it and do things.

For the new keyword, it’s how objects are created dynamically.

You can have for example:

Waypoint wp = GetComponent<WayPoint>();

This creates a reference variable ‘wp’ that can point to a WayPoint object, and here we’re assigning an existing one to it.

But what if one doesn’t exist yet? This wouldn’t work:

Waypoint wp;

print(wp.GetGridPos());

It would complain that ‘wp’ doesn’t actually point to anything, it is null. It first has to be created, and then assigned to wp before it can be used.

Waypoint wp = new Waypoint();

Now it is created AND assigned to wp, so you can call methods to interact with it.

4 Likes

Thanks Topdog. Your explanation of RequireComponent and Getcomponent was top notch. It is much clearer to me know. Thanks for helping with “new” as well. Still not quite getting it, but will persevere.

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

Privacy & Terms