- Home /
Detect with Object has been triggered
Hello there,
I'd like to check which Object got triggered by the player, but nothing happens with my script.
void OnTriggerEnter(GameObject touched)
{
if(touched.name == "Trigger_Start")
{
startTime = Time.time;
}
if(touched.name == "Trigger_Finish")
{
finished = true;
startTime = 0;
}
}
Anyone knows how to do it?
Greetz, ITGeist.
Answer by azmat786n · Dec 09, 2012 at 04:41 AM
//if not work change OnTriggerEnter-->OnTriggerStay
void OnTriggerEnter(GameObject touched)
{
if(touched.name == "Trigger_Start")
{
Timer += Time.deltaTime;
startTime = Mathf.RoundToInt(Timer);
}
if(touched.name == "Trigger_Finish")
{
finished = true;
startTime = 0;
}
}
you need to make 2 variables with name of
var Timer:float; var startTime:int;
Answer by devain · Dec 09, 2012 at 11:23 AM
Using a string compare is quite expensive. I would suggest you compare by reference instead, something like this:
void OnTriggerEnter(Collider other)
{
ObjectToLookFor reference = other.GetComponent<ObjectToLookFor>();
if ( reference != null )
{
// Do fancy stuff, like comparing the name - if you really really have to
}
else
{
// Do stuff that didn't require this type of object
}
}
Answer by SinPin · Dec 09, 2012 at 11:22 AM
Hey ITGeist ;)
You should know some details about the trigger system:
1st: The Prototype of OnTriggerEnter is not "void OnTriggerEnter(GameObject touched)", but " void OnTriggerEnter(Collider other)" as you can read here
2nd: There are some things, you have to do in the Unity Editor...
All your Objects, you want to use as trigger, should have a Rigidbody (Component -> Physics -> Rigidbody) - Set the "Use Gravity" flag to false (unticked) if you do not want it to act as a normal rigidbody.
And all your objects should have a collider (e.g. BoxCollider) (Comes automatically with the standard objects, if you don't have it: Component -> Physics -> e.g. Box Collider) where the "is Trigger" Flag is set to true (ticked). (Actually only one of the colliding objects must have set the Trigger-Flag to true, but every object needs to have a collider.)
I hope, this helps you ;)
Yours, SinPin
Your answer
Follow this Question
Related Questions
Play parent animation without affecting the child animation 1 Answer
Trigger Script Not Firing 4 Answers
how to make triger fireball not to pass through spesific objects 2 Answers
How to trigger a Script from an Object. 0 Answers
Triggered box works automatically for OnMouseEnter for objects inside. 0 Answers