Cannot properly access player position
I have been trying to make an enemy script that cause the enemy to move towards the player. As far as i know i'm accessing the player object properly but my position variable always returns 0,0 which i suspect is null. My enemy object always moves towards 0,0,0 below is my script please could you have a look and see what i'm doing wrong? I'm new so please try and explain why I'm wrong as well but if you don't have the time, thanks anyway :)
PS: My player object does have the tag "Player" on top level and has a transform attached
using UnityEngine;
using System.Collections;
public class enemyControllerA : MonoBehaviour {
public GameObject target;
public float speed;
Vector2 playerPos;
void Start () {
target = GameObject.FindWithTag ("Player");
}
// Update is called once per frame
void Update () {
playerPos = new Vector2(target.transform.position.x,target.transform.position.y);
float step = speed * Time.deltaTime;
transform.position = Vector2.MoveTowards (transform.position,playerPos,step);
print (playerPos);//always returns 0,0?? why god why!!!!
}
}
Answer by Zee-Play · Feb 22, 2017 at 12:13 PM
Make sure you have your "Player" tag created and assigned your player object that tag.
Well, I ran your script and it works for me, that's why I assume the problem might be in the inspector.
I have read in a few places that it is a bug and an asset reimport might help but it didnt - the only thing i have recently changed was add animations to player, although i dont see that affecting it
Your answer
Follow this Question
Related Questions
Vector3.MoveTowards moving transform 0 Answers
How to find the transform position of another gameobject then move a gameobject to that position? 1 Answer
When hitting border teleport bullet to player. 1 Answer
How to get the position of a gameObject based on its index in an array? 0 Answers
How To Make An Object Appear In Front Of Player Without Cloning? 1 Answer