How to override codes from the inherited script

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Idleman

I am having a bit trouble to understand how inherited works. In my game, I have created an enemy A, when A detects the player, it runs towards the player and hit it. Then there is an enemy B, I made it an inherited scene from A, and extend the A script to make script B.

Basically, B has the same behaviour as A, only when in a Chase state, I want B to stay in current position and shoot instead of going towards the player. However, I am not sure how to rewrite the codes for chase state in script B that overrides the code in base script A.

I just copy the code from Chase state from A to B, update the code, but enemy B still follows some behaviour from script A. In case like this, what is a good way to update codes for enemy B? Thank you.

Thats actually how you do it. You simply overwrite the functions.
Seems the problem comes from your Implementation.

Can you supply some code?

klaas | 2020-07-24 11:31

1 Like
:bust_in_silhouette: Reply From: Vincent Grossmayer

Simply write a function in B that is named the same as the one you want to overwrite from A.

But to be honest, it seems like an architectural flaw. Because why would you want to inherit a class, but have it behave completely different?

Maybe an architecture like this would make it easier to maintain and extend:

Make a base class A which basically only detect a player and write the target into a virable.

Inherit from class A for you enemy follower, there you can implement the logic to follow the set target.

Inherit from class A for your shooting enemy, there you can implement thew logic to only shoot at the target.

This way you have every functionality isolated in their own functions.

Thank you for your advice, I went back and check my code and found the problem. In attack state, A script has Attack melee function, and in B I rename it with Attack shoot, I forgot the name has to be the same. This time I make the function name just attack, and update the code, it works and the B scripts overrides the func with the same name.

The method that you are suggested has its advantages and some tutorials are using it. As for my game, I have 4 types of enemy, type A and B are identical, only the attacking mode is different, so I plan to have a script A for enemy A and inherited it to make script B for enemy B, and I only need to update the code to override some part of A. For me, this is a similar concept to a custom css file over a theme file. I personally found this is easier to manage.

Idleman | 2020-07-25 04:54

1 Like