- Home /
Get enemy position in script
I want to get the x,y,z position of a GameObject with the name Enemy in a script. The script is attched to a player object.
I get an error " The name `Enemy' does not exist in the current contextThe script is not attatched to the Enemy game object."
GameObject enemy = GameObject.Find ("Enemy");
//then i want to get x,y,z posotion of this Enemy
http://unity3d.com/support/documentation/ScriptReference/GameObject.Find.html
What am I doing wrong?
Help us out and post code snippets. Its hard to understand what exactly is going wrong when we have to wonder. That error pretty much means that the variable youre using isnt in the parameters of the function. Did you spell the Enemy name different in any way?
There a cube I have name Enemy . This code below is attached to the player and it doesnt know what enemy is?
void Start () { GameObject enemy = GameObject.Find ("Enemy"); }
// Update is called once per frame
void Update () {
enemyx=enemy.transform.position.x; //error here
}
Finding GameObect....("Enemy"); will find one enemy named "Enemy" , so if the name of the object is not Enemy, the return will be null. Double check the actual name of the object jic.
I have a Cube I called Enemy. The name Enemy appears in the hierarchy and in the inspector on top left.
are you sure its not 'enemy' ins$$anonymous$$d of 'Enemy'? that the error is looking at? You have the GameObject enemy locally declared in Start(). And then trying to execute it in a separate function; Update(). $$anonymous$$ake the declaration global and see what it does.
Answer by jtbentley · Jun 05, 2012 at 02:22 AM
This should work, it's JS but minus the declarations it should work a treat.
private var enemy : Transform;
private var enemyX = 0.0; // Set this as a float
function Start()
{
enemy = GameObject.Find("/Enemy").transform;
}
function Update()
{
if (enemy) enemyX = enemy.position.x; // We check to make sure the object exists before we go pulling data from it
}
You can also protect against the null on the Start() with try { enemy = GameObject.Find("/Enemy").transform; } catch (err) { print ("The object didn't exist"); }
Your answer
Follow this Question
Related Questions
Compare Position of two gameobjects and if true, do nothing, help me please! 1 Answer
Different Position (Object position - Mouse Position) 1 Answer
Moving GameObject to various position ? 1 Answer
Initializing Prefab Position 2 Answers
Object's sprite and collider are not at same position as transform 1 Answer