- Home /
Can't get the gameObject is inside Physics2D.OverlapBox
The situation is this: a 2D arcade game with a hero and some enemies. One attack is to jump over the enemies. I am trying to use the same code is detecting if the hero is grounded (so he can jump) to detect the hit over the head of enemies:
testePisoPos = new Vector2(Pe.transform.position.x, Pe.transform.position.y);
Collider2D obj = Physics2D.OverlapBox(testePisoPos, testePisoDim, 0f);
if (obj != null)
{
estaNoChao = obj.gameObject.CompareTag("piso");
if (obj.gameObject.CompareTag("demonio"))
{
GameObject Hit = Instantiate(TestePos, testePisoPos, Quaternion.identity);
Destroy(Hit, 1f);
Vector2 v = this.gameObject.GetComponent<Rigidbody2D>().velocity;
this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(v.x, 2);
List<Collider2D> Colls = new List<Collider2D>();
int nColls = obj.OverlapCollider(new ContactFilter2D(), Colls);
for(int i=0; i<nColls; nColls++)
{
print("Herói dando toco no demônio " + Colls[i].gameObject);
Colls[i].gameObject.GetComponent<skeletonMove>().TocoNoCoco();
}
}
}
else
{
estaNoChao = false;
}
estaDoChao means "is grounded", happens when there is some element below with tag "piso". Pe is a child GameObject from where I will test, it is below the hero's feet. Hit GameObject is just a sprite that allows me to see if the collision is happening where it supposed to be - and it is. This code is working so far, the collision happens and the hero jumps back.
The problem is when I will get the enemy's GameObject so I can call it's TocoNoCoco() function that will make the damage in the enemy. Every time I hit the enemy's head, the print return is one GameObject that is the ground below the enemy. And, of course, there will be an erro in the following line because the ground got no TocoNoCoco() function.
The strange thing is obj.gameObject.CompareTag("demonio") matches the enemy's tag: demonio, but the obj.OverlapCollider returns a GameObject tagged as piso... whyyyyy???? How can I avoid this?
Your answer
![](https://koobas.hobune.stream/wayback/20220612202637im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Collider of Platform Effector overlap Problem 1 Answer
Make colliding object not collide in overlapped area 0 Answers
Getting Collider2D.bounds.extents to update immediately (2D) 0 Answers
Overlapping colliders problem - causes player to bounce 1 Answer
Checking for Colliders with Physics2D.OverlapBoxAll Won't Work? 0 Answers