- Home /
Trigger moves another object
What I basically want to do is move an object when I collide with a trigger. In my scene I have a trigger that when it is collided with, you will see an object in the distance move diagonally upwards.
Here is what I have so far:
var box : GameObject; var Speed : float;
function Update () {
var translation : float = Time.deltaTime * Speed;
box.transform.Translate (-translation, translation, 0);
}
function OnTriggerEnter (other : Collider) {
Debug.Log("trigger");
}
My only issue is that I can't move the box upwards upon collision with the trigger if box.transform.Translate isn't in function Update() along with the line of code above it.
and I can't stick OnTriggerEnter in function Update.
I want to be able to place this trigger separately from this moving object, but it's proving to be trickier than I originally thought..
When posting code next time, please highlight it, and push the 10101 button up top =). Thanks!
Answer by Ben Holmes · Apr 06, 2011 at 12:03 AM
looks like you need two seperate objects in the scene. I would create two seperate scripts for this kind of behaviour. One which is attached to the trigger and uses the OnTriggerEnter method, and another which is attached to the box and uses the Update function.
The trigger script should get a reference to the other script in it's Start() function (there are a number of ways to do this). and when the trigger is entered you can simply set a bool on the box script. In the box script's Update() function you only want to translate if the bool member is true. Here's an example:
class BoxScript : MonoBehaviour { public bool moving = false;
void Update() { if(moving) { var translation : float = Time.deltaTime * Speed; box.transform.Translate (-translation, translation, 0); } } }
class TriggerScript : MonoBehaviour { BoxScript otherScript; void Start() { BoxScript = GameObject.Find("Box").GetComponent<BoxScript>(); }
void OnTriggerEnter() { otherScript.moving = true; } }
the scripts aren't working for some reason.. Originally I was trying to do all this with one script, but I might just go with two to make it simpler.
Your answer
![](https://koobas.hobune.stream/wayback/20220613120951im_/https://answers.unity.com/themes/thub/images/avi.jpg)