#Get Component doesn't work when there are multiple objects with the component

1 messages · Page 1 of 1 (latest)

vocal echo
#

I have a player script that is doing an attack, and a keyframe of the animation I call the Attack() method. The method does a Physics2D.OverlapCircle check in front of the player. If an object connects with the circle, I currently have it run enemy.GetComponent<Health>().Test();, which runs a method where the only line is Debug.Log("Does");. I know that's probably obvious from the screenshots shared but making sure it's understood what is going on

So, I put the Health component onto an enemy, the player performs Attack() and it works... when there's 1 instance of a gameobject with the script. If I have to objects with the Health component, only one of the objects will actually have the Test() method run. I've looked up online for some help, but I'm only getting tips for when there's multiple components on ONE game object rather than when there's multiple OBJECTS that have the same component

Am I missing somethin here?

zealous grotto
#

enemy.GetComponent<Health>() will get the Health component from whatever enemy is.

#

If enemy has a Health component, that will get it.

#

If it does not have one, it will return null, which will throw a Null Reference Exception when you try to call .Test() on null

snow ether
#

Also that overload of Physics2D.OverlapCircle only returns one object. Try checking the physics2d docs to see if there is a method or overload that returns more than one or has some way of filling a list/array with more than one

vocal echo
zealous grotto
vocal echo
#

There are 2 enemies but I'm only hitting them one at a time

zealous grotto
#

enemy is a single specific object

#

And you're getting that object's health component

vocal echo
#

Sorry I'm still new to unity, trying to get back into it

snow ether
#

which is why i said to check the docs to find what you need

zealous grotto
#

The issue isn't with GetComponent. It's doing exactly what it's supposed to do.

vocal echo
#

Okay, doing it like this works it looks

snow ether
#

why are you still checking if enemy is not null inside of the foreach loop that loops over enemy?

#

also you might want to consider using a non-allocating version (like the overloads of OverlapCircle that you can pass a list or array into to populate)

vocal echo
snow ether
#

look at the docs for Physics2D.OverlapCircle

vocal echo
#

I'm not that familiar with allocators so I'm not sure what I'm looking for

snow ether
#

there are three overloads for OverlapCircle. I told you to look for one that allows you to pass in an array or list. Of the three available ones, which do you think that might be?

vocal echo
#

Would I be able to do either of these?

snow ether
#

yes. just make sure to actually read the documentation so you understand how to use them