Tags vs Inheritance

Hello and first of all thank you for this fantastic course!

Question is about Section 5 : Block Breaker of the Unity 2D course.

I have a little bit of object-oriented programming knowledge and was wondering how to use inheritance instead of using tags for the different types of blocks.

I’ve researched the course Q&A, and I know inheritance is not on the agenda, but I’d still like to understand how it could work.

I know I could have the Block class, and then the BreakableBlock class that would inherit from Block (and implement OnCollisionEnter2D ).

Could someone simply explain to me how I could do this with the example of blocks? While keeping the simplicity of prefabs and drag and drop. I can’t wrap my head around it !

Thanks in advance !

Hi,

Welcome to our community! :slight_smile:

Inheritence is not covered in this course. However, if you know how to make classes inherit in C#, you could write a base class for the blocks and make the other block classes inherit from that class. It’s not complicated.

Prefabs don’t have anything to do with your idea. You could simply assign our BreakableBlock class to the prefab or game object. Just make sure the Block class inherits from MonoBehaviour.

You can find tutorials on Youtube.

Please feel free to ask our helpful community of students for advice in our official Discord chat.


See also:

Thank you Nina for this quick answer ! I’ll watch the video you provided closely :slight_smile:

Yeah I know how to do that :wink:

My question was more of a “How can I make this work with prefab” :

So, if I create this BreakableBlock class, transfer all the code I think belongs to BreakableBlock from Block, and then create my “BreakableBlock” prefab, do I have to attach both scripts to it? Block AND BreakableBlock? Or does the simple fact of attaching BreakableBlock also implicitly give me access to, for example, the [SerializedField] of the Block class?

A prefab is nothing but a game object which exists as a file in your Assets folder. Unlike objects in your scene, it’s not in your scene. That’s all.

Since BreakableBlock inherits from Block, there is no need to attach an additional Block object. BreakableBlock objects are also Block objects, extended Block objects. The Block class must inherit from MonoBehaviour. Then BreakableBlock inherits from MonoBehaviour, too, and you can use [SerializeField].

Test it with a single field. Then extend your Block and BreakableBlock classes as needed.

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

Privacy & Terms