1
\$\begingroup\$

Let's say I'm writing 3D Pacman. I have "Dot" objects throughout my maze, that are structured as follows in the Inspector:

Dot (GameObject)
- Sphere w/Collider

When I run into the sphere trigger, I can trivially say:

"Get me your parent and check if it's a Dot"

However, I hate baking in the knowledge that some spheres have parents that are Dot objects. If the trigger were on the Dot itself that problem would solve itself, as I could just call GetComponent().

What's a good programmatic style approach to finding out what logical Game Object actually owns the geometry you've collided with? I could add a Tag of "Dot" to the sphere but that's just a level of confirmation, I still would have to walk up to it's parent and check.

\$\endgroup\$
1
  • \$\begingroup\$ Why does the collider have to be on the child? \$\endgroup\$ Commented Nov 5, 2016 at 5:45

2 Answers 2

1
\$\begingroup\$

I have done similar in a few projects... and using Tags (on both parent and child) would be the easiest way (I think). On the collision trigger detection you could do a comparetag like this one :

if (hitColliders.gameObject.CompareTag("TagName"))
{
do your stuff here if tag match;
}

I am also unsure why there is a "sphere" as a child... is it invisible and only there for the collision? If that is the case, I would get rid of the sphere and put the sphere-collision directly on the dot itself... that would make it way easier if you had to do a Destroy() after collision with tag "player" :)

\$\endgroup\$
0
\$\begingroup\$

There are multiple ways to do this.

  • Check in a HashSet, a simple way of doing this behaviour without the overhead or complexity would be to just add each dot collider to a hashset then when you collide with a sphere collider you check the hashset if the collider is in there. Since it's a hashset very few objects will need to be compared to get the result so it would be fast and you wouldn't have to check the parent at all as the colliders themselves would be added to the hashset. All the computation of finding the dot would be at the start or possibly hidden in a loading screen or even though a coroutine (depending on how you choose to search for dots)...
  • Create a script called Dot (for example) you could then add this to the dot object and do a getComponent on it to check if it's a dot.
  • Rename to collider, though this would be similar to just having a tag or having the sphere collider on the parent object in the first place.

I'm sure there are many other ways of doing this, these are just of the top of my head.

Hope this helps :)

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.