Clarification on CanAttack()

Hey all. I’d appreciate if someone can clear something up for me (Screenshot from Rick’s screen)

image

Is testing targetToTest for null just good programming practice here, as a just in case measure of sorts? Wouldn’t the RequiredComponent(Health) parameter in CombatTarget.cs prevent this from returning null since all CombatTargets are required to have Health on them?

Sorry if stupid question

I haven’t done this course, but I think this is just force-of-habit. It is, however, never a bad idea to make sure an object is not null before calling methods on it unless you are 100% certain it will not be, like when you just created it

1 Like

It’s a good habit to be in, always null check targets even if you’re positive it’s impossible for them to be null. Believe it or not, it’s not always a given.

For example: Any GameObject with a CombatTarget that was created before you added

[RequireComponent(typeof(Health))]

to CombatTarget will not automagically get a Health component. It will only be added to GameObjects in which you ADD a CombatTarget.

1 Like

Thanks for clearing that up folks!

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

Privacy & Terms