trigger

I wanted to make a script so that my main character when collide with a cube automatically changes direction. The player is on the z axis with a force equal to 2 and collide when to go to -2. This is what I did but it does not work

#pragma strict
var bonus : GameObject;
var collisione : GameObject;

function Start () {

}

function Update () {

rigidbody.AddForce(0,0,-2);

}

function OnTriggerEnter (collisione : Collider) {
Destroy(bonus.gameObject);

(gameObject.tag == “Player”) {
rigidbody.AddForce(0,0,2);

}

When you set the addForce in the Update function, it will run in every frame no matter what.
So when your trigger function is called, it will merely add a force in the other direction for the duration of the collision, witch is only one frame, since the colliding object is destroyed immediately.
Use a virable instead, and change it’s value when the collision occurs.

var bonus : GameObject;
var collisione : GameObject;
var force : int = -2;

function Update(){
   rigidbody.AddForce(0,0,force);
}

function OnCollisionEnter(collisione : Collision){
  if(theCollision.gameObject.name == "Player"){
    force = 2;
     Destroy(bonus.gameObject);
  }
}

This is my code:

var bonus : GameObject;

//var collisione : GameObject;

var force : int = -2;

function Update(){

rigidbody.AddForce(0,0,force);

}

function OnCollisionEnter(collision : Collision){

if(gameObject.bonus == “Player”){

// force = 2;

Destroy(gameObject);

}

}

I do not understand why it does not work

please use [ code brackets…

I suppose you know that // means comment in a script, right? you shouldn’t lock out that piece of the code.

var bonus : GameObject;

//var collisione : GameObject;

var force : int = -2;



function Update(){

rigidbody.AddForce(0,0,force);

}



function OnCollisionEnter(collision : Collision){

if(gameObject.bonus == "Player"){ //this line is just wrong. make it if(collision.gameObject.tag = "Cube")
      //then tag all cubes you wan't to do this as Cube.

force = 2; //removed the comment lines

/*if you want it to go back and forth, you could replace the previous line with this:
if(force==2){force = -2;}
else {force = 2;}

*/

Destroy(gameObject); //this line will destroy the object that holds the code

}

}