- Home /
OnTriggerEnter Not Working
I am trying to use the following code to execute an action when my player collides with a certain object, but I can't seem to get it to work. I have the collider on the object the player should collide with as "Is Trigger", and the script is attached to the same object.
function OnTriggerEnter(other : Collider)
{
if (other.name == "First Person Controller")
{
Debug.Log("collision");
}
}
EDIT: Got it working, I feel smart. :P Here is my finished code below for anyone who may need something like this.
var target : GameObject;
var inside : boolean;
function OnTriggerEnter(other : Collider)
{
if (other.tag == "Player")
{
var ph : PlayerHealth = target.GetComponent("PlayerHealth");
ph.AdjustCurrentHealth(-1);
inside = true;
}
}
function Update() {
if(inside)
{
var ph : PlayerHealth = target.GetComponent("PlayerHealth");
ph.AdjustCurrentHealth(-1);
}
if(!inside)
{
Debug.Log("Not colliding");
}
}
function OnTriggerExit(other : Collider)
{
if (other.tag == "Player")
{
inside = false;
}
}
Answer by jmatthews · Feb 23, 2013 at 12:37 AM
Does the object the trigger is reacting to have a rigidbody?
is the player object moving? The physics engine puts rigid bodies to sleep when they're not moving and you'll get no collision detection. Try walking the player object into the laser beam. If you get your event to fire then this is your issue.
Somehow it seems to be working now, but I still have another small issue. When the player collides the first time, it executes the action perfectly, but I need it to continue to execute the action while the player remains inside of the object.
Looks like you figured the OnExit out on your own, congrats. Please accept whichever answer helped you so this gets out of the unanswered stack.
Answer by TheCheese · Feb 23, 2013 at 01:11 AM
Triggers require at least one of the objects involved to have a Rigidbody component. Check out the collision matrix at the bottom of this page for more info:
http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html
Answer by vincysq96 · Feb 23, 2013 at 12:57 AM
Try using:
if (other.tag== "Player")
and assign a tag "Player" to the First Person Controller
I changed the script to this, and accidentally had the collider checked off for the other object. When I turned it on, the collision just crashes unity and I have to end it with the task manager. Essentially, I want the player to be able to walk through to object (it is a laser beam) and take damage when he touches it. I already have the code to lower his health, but how should I handle the collision?
Your answer
Follow this Question
Related Questions
Colliding two GameObjects 1 Answer
Compound collider does not trigger the parent 1 Answer
Trigger Spawning? 1 Answer
Can't click gameobject when over another trigger? 1 Answer
Collision with renderer.enabled? 0 Answers