Trouble with getting cube to follow character

Hi all,

at the moment I have two scripts (Hills_Cube_Collide.js, Follow.js) The first script sets the target of the cube to ‘Player’ when the character hits the cube, but only if that cube has the tag ‘Cube2’. The second script is where the code for the cube to follow the character goes. Now here is my problem. I have two cubes on the screen both with the tag ‘Cube2’, so what I want to happen is when i intersect one cube, that follows me, and then when i hit the next cube that follows me also. But what is happening is no matter which cube i hit, they both start to follow me at the same time, they don’t wait until they have been hit. For example, if i hit the cube on the left; the one on the right will also follow. Whereas what I want to happen is that the cube follows me when i hit it, not when i hit a cube with the same tag as it…any suggestions would be appreciated!

Hills_Cube_Collide:

function OnTriggerEnter (other : Collider) { 
if (other.gameObject.tag == "Cube1" ){
	//Destroy(other.gameObject);
//	other.Parent = Player;
   Score.score += 1;
   Follow.target = GameObject.FindWithTag("Player").transform;
   }
}

Follow.js

    static var target : Transform; //the enemy's target
    var moveSpeed = 3; //move speed
    var rotationSpeed = 3; //speed of turning
   
     
    var myTransform : Transform; //current transform data of this enemy
     
    function Awake()
    {
    //myTransform = transform; //cache transform data for easy access/preformance
    }
     
    function Start()
    {
    //target = GameObject.FindWithTag("Player1").transform; //target the player
     
    }
     
    function Update () {
    
    if (target == GameObject.FindWithTag("Player").transform)
    {
	//rotate to look at the player
    myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
    Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     
    //move towards the player
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
    }
     
     
    }

You have the ‘target’ variable set as static, which means it is shared by all instances of that class, and when you set it for one cube, you set it for all cubes. To fix this you need to first change the decleration of ‘target’ to non static:

var target : Transform; //the enemy's target

and then change how you set that value on collision:

    function OnTriggerEnter (other : Collider) {
       if (other.gameObject.tag == "Cube1" ){
          Score.score += 1;
          var followScript: Follow = other.gameObject.GetComponent("Follow");
          followScript.target = GameObject.FindWithTag("Player").transform;
       }
    }

Lastly, in your question you say the cubes are tagged as “Cube2”, and in the script they’re tagged as “Cube1”, so you may want to check that. Let me know if this works or not, I use C# so there may be some minor syntax errors.