0
\$\begingroup\$

I'm trying to set up a proximity warning system but I'm having some trouble.

To simplify things as much as possible:

I have two game objects in a scene (Object1 and Object2). Object1 has a large child object (twice as large as Object1 or Object2) which has no mesh renderer, but has a box collider (with the Is Trigger box ticked). Object 2 has a rigidbody component.

When Object1 gets close enough that it's child's Box Collider overlaps with Object2's rigidbody, a script on Object1 should Debug.Log the name of the object it's close to once a frame until Object1 moves away.

My code is as follows:

public Collider objectCollidedWith;

void OnTriggerStay(Collider other)
{
objectCollidedWith = other.transform.GetComponent<Collider>();
}

void Update()
{
Debug.Log(objectCollidedWith);
}

Unfortunately, something about my setup isn't working. The console just shows "null" once a frame and the objects getting close doesn't change this.

Can you tell me what I'm doing wrong?

Many thanks for your time.

\$\endgroup\$
3
  • \$\begingroup\$ It is true that for a Trigger and/or Collision to happen, at least one of the two objects must contain a Rigidbody component, as you are doing, but both objects must contain a Collider component, and must be able to detect intersections (if you didn't move the physic settings' collision matrix, you don't have to worry about that step). Try first debugging inside OnTriggerStay, so you can know there is a trigger to begin with. \$\endgroup\$ Mar 18, 2019 at 18:35
  • \$\begingroup\$ And one advice, maybe a little bit off-topic. It is redundant that you get the Collider component from the gameObject that contains the Collider "other" passed as the parameter, you can just set your objectCollidedWith variable equal to other. \$\endgroup\$ Mar 18, 2019 at 18:36
  • \$\begingroup\$ Can you edit your question to show us your setup of the two bodies, and how you're moving them? As an aside, other.transform.GetComponent<Collider>(); this is a very strange way to just write other; \$\endgroup\$
    – DMGregory
    Mar 18, 2019 at 18:37

1 Answer 1

1
\$\begingroup\$

If the script is ON object1, and the trigger is on the CHILD, then it will not bubble up to the script, unless you put a rigidbody on object1. A collider without a rigidbody, only broadcasts the collision messages to the gameObject the collider is on. A collider with a rigidbody anywhere in its parents, will broadcast the message to the gameobject that the rigidbody is on.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .