Confused about Classes and Object Types

I’m getting a little confused about the use of Types inside code.

In this lesson, for instance, in the Attacker class, we used

GameObject currentTarget

to store the target. But sometimes we use the classes we’ve created to define variables and attributes, like:

Attacker attackerPrefab
Defender defenderPrefab
Defender newDefender = Instantiate(…) as Defender;

and so on. When to use GameObject and when to use our classes? What’s the difference?

Could this lesson example be

Defender currentTarget

instead of GameObject currentTarget?

And another question. When we define a Serialized Field to store a prefab, like the examples above, sometimes, when I open the field in the inspector, I get a list of filtered list of prefabs for the defined type, sometimes I get nothing, only an empty window. Why does this happen?

I’m using Unity 2020.1.3f1 Personal, BTW

Hi Rodrigo,

Welcome to our community! :slight_smile:

GameObject is the wrapper for all components. The associated object in Unity is the game object in your Hierarchy (or a prefab in your Assets folder). When you click on it, the Inspector shows the “content” of the selected game object.

Use the GameObject type if you intend to access multiple components of a game object. Use the type of a specific component when you intend to access only that component.

If your target game object has got a Defender component attached and if you need to access that Defender instance, you may use the Defender type. If the game object has got an Enemy component and you need to access that instance, use the Enemy type.

It might be that Rick declares a variable of type GameObject just to access a component of it via GetComponent at a later juncture. My advice is to simply test your ideas because in many cases, there are multiple ways to make something work in Unity.

Regarding your second question, it depends on what type you declared. If Unity cannot find any object of that type, the list remains empty. Did you notice the two tabs, “Asset” and “Scene” (or something like that) in the pop-up window? “Scene” refers to the Hierarchy, “Asset” to your assets folder.

Did this clear it up for you? :slight_smile:


See also:

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

Privacy & Terms