Why this piece of code

Rick used this piece of code in script
‘’’ if(attacker && health) :thinking:
{
health.DealDamage(damage);
Destroy(gameObject);
}
‘’’
But why we are checking attacker and health scripts’ presence, when if Enemy exists which holds both of them. Then there should be no point of writing this piece of code

Hi,

How can you ensure that the enemy contains an Attacker component and a Health component during runtime if you don’t check that via code during runtime?

But mam @Nina we are adding those scripts in GameObject in prefabs. Is there any chance that our enemy can lose them.

The chance is “we”. Humans make mistakes. For this reason, it’s a good idea to have the program check if objects exist before accessing those objects. Otherwise, we risk getting errors which freeze our game.

1 Like

I found next video we are adding a game play area with a 2D collider which will also collide with the our projectile. So for that we are checking that if we collide with a gameObject which is having both the scripts " attacker and health" than only we have to call dealDamage function and destroy and our projectile “Zuchinni:smiley:

Thanks alot mam @Nina for your words. This will definitely be very useful in my game dev journey.

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

Privacy & Terms