#Bad / dumb code

1 messages · Page 1 of 1 (latest)

mental void
#

if(player.GetComponent<someScript>()!=null){
player.GetComponent<someScript>().ApplyDamage();
}

why is this code bad / dumb?

queen spear
#

Because you're calling GetComponent twice

#

on the same thing

#

use TryGetComponent instead

mental void
#

can you explain more please

queen spear
#

Which part, why it's bad? Or do you mean an example for TryGetComponent

mental void
#

yeah example

#

on trygetcomponent

fresh fulcrum
mental void
#

if i use try get component then how would call the method that is in component?

queen spear
#

The docs give an example for that

#
if (TryGetComponent(out HingeJoint hinge))
{
    hinge.useSpring = false;
}
mental void
#

i do not quite understand the parameter that is given to this function like out thing cause that is used in raycast i think

mental void
#

ok what method would be better if there is no such thing as trygetcomponent in above code

queen spear
#

There is tho

mental void
#

assume that its not available i mean

queen spear
#

Why would I assume that

#

You're literally already calling GetComponent. If you can call GetComponent, you can call TryGetComponent

mental void
#

alright thanks for your time and help @queen spear
@fresh fulcrum appreciate it guys