- Home /
 
Game object position.
Hi - I am a serious noob as far as coding goes, just taking my first steps in javascript. What I am trying to do is find the position of another gameobject (tagged with unit), and then act upon it. I understand the code snippeet below is probably wrong on a multitude of levels, but any help would be appreciated!
function Start () {
}
var Unit1 = GameObject.FindGameObjectsWithTag ("Unit"); var dis : float;
function Update () {
  if (Unit1.transform.position.x==3)
  {
  debug.log("done");
  }
     
 
               }
What do you mean by "act upon it"? What is it you are trying to do?
Answer by Vonni · Jan 18, 2013 at 05:38 PM
EVEN EASIER FIX:
 var unit1 : GameObject;
 // and then drag GameObject inside this variable in the inspector
 
               EASY FIX:
 // Look for objects name instead: (Unit)
 var units : GameObject;
 function Start(){
     units = GameObject.Find("Unit");
 }
 
               HARD FIX:
 var Unit1 = GameObject.FindGameObjectsWithTag ("Unit");
 
               This doesn't work, because GameObject.FindGameObjectsWithTag is a function in the GameObject class that RETURNS an array ( GameObject[] ).
So instead do something like this:
 var units : GameObject[];
 function Start(){
 units = GameObject.FindGameObjectsWithTag ("Unit");
 }
 
               But now the next code is going to be wrong, and its also inside Update(), so it will be called for every game frame. Which would spam your console :S
  if (Unit1.transform.position.x==3)
  {
  debug.log("done");
  }
 
               So do something like this instead now, im doing it in Start() for now:
 var units : GameObject[];
 function Start(){
 units = GameObject.FindGameObjectsWithTag ("Unit");
 for (var i : int; i < units.Length; i++){
 if(units[i].transform.position.x == 3){
 debug.log("done");
 }
 }
 }
 
              Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Slicing Objects 1 Answer
Object position question... 0 Answers
how to scale an object in order to fix the screen dimensions 3 Answers
End game then an Object is close to another object? 0 Answers