- Home /
How to call a OnTriggerEnter function in a Update function?
How can I get (In Javascript) a OnTriggerEnter function in a Update function for a Enemy AI. This is the code: var target : Transform; var moveSpeed = 3; var rotationSpeed = 3; var myTransform : Transform;
function Awake() { myTransform = transform; }
function Start() { target = GameObject.FindWithTag("Player").transform; }
function Update(){
transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z));
myTransform.Translate(Vector3.forward moveSpeed Time.deltaTime);
}
BTW if you know a way to make this code smaller please say it.
Answer by m4s4m0r1 · Oct 06, 2012 at 02:12 PM
Impossible... Because OnTriggerEnter and Update is a different function. So, the function cannot be called in another function. If you want to do that you can make a variable to solve that For Example : if you want to call that Trigger was true. here it this
var yourVar = false;
function OnTriggerEnter(other : Collider)
{
yourVar = true;
}
function Update()
{
if(yourVar)//if yourVar is true
{
//do something in here
}
}
how to write this in c#? i am an absolute beginner when it comes to codes...
You probably shouldn't, but here it is:
public class $$anonymous$$yClass {
bool yourVar;
void OnTriggerEnter (Collider other){
yourVar = true;
}
void Update () {
if(yourVar){
// Do something
}
}
}
Thanks a lot... so it is actually BOOL ins$$anonymous$$d of var...
Answer by Dragonlance · Oct 06, 2012 at 02:54 PM
Shinxs you need to think in form of events.
Sure you can move the rocket or whatever in Update and if that move resulted in a collision with a trigger, then OnTriggerEnter will be called and you explode it there.
You do not need to check if a collision happened in Update. You can of course do it i.e. with RigidBody SweepTest() SweepTestAll() but you do not have to.
Anyway for such stuff to work both game objects need to have a rigidbody and collider attatched and one has to be flagged with IsTrigger if you want to use OnTriggerEnter.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081945im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Calling OnTriggerEnter every update if something is false 0 Answers
OnTriggerEnter not working 5 Answers