[Tip] Referencing the Monobehaviour in the Prefab instead of the Transform

Just a small tip I’d like to leave here: I haven’t seen the rest of the course yet, but it is usually simpler and less error-prone to use a specific script when referencing the Prefab instead of the Transform - in this case it would be GridDebugObject

So, in Testing.cs you would have

[SerializeField] private GridDebugObject debugPrefab;

The main advantage is that you can only assign prefabs containing the component to that field. So you won’t get an issue when trying to get it later. And in GridSystem.cs, you could have

public void CreateDebugObjects(GridDebugObject debugPrefab)

When you instantiate the debugPrefab, you no longer need to get the component. If you need the transform you can always do gridDebugObject.transform

Not sure if this has any drawbacks though, so please reply if you know of any. Thanks!

1 Like

I saw this a lot in the RPG course as well(which was 2-3 years ago and almost the start of my gamedev journey so its a BIT fuzzy).

Almost always references the scripts and almost never the transform.

It’s a good tip, but it also depends on the use case. If you want the transform, you’d reference the transform. But what if I want, say, the player controller and the health from the same object. I can make two fields - one referencing player controller and one referencing the health - or I could just reference the transform/game object and get both from there.

Absolutely.

I like to reference what i am using myself. I’d grab each component separately just so I know what I am using, but as always, there are exceptions.

1 Like

Privacy & Terms