Enemy AI Script Error
Hi guys currently I'm trying to create a 2D top-down game. This enemyAI script is trying to find the players game object with tag named "Player"but currently I'm getting a specific error shown in an image below.
Is there a simpler way to do an enemy AI script?
public class EnemyAI : MonoBehaviour {
private Vector3 Player;
private Vector3 playerDirection;
private float Xdif;
private float Ydif;
private float speed;
private int Wall;
// Use this for initialization
void Start () {
Wall = 1 << 8;
speed = 10;
}
// Update is called once per frame
void Update () {
Player = GameObject.FindGameObjectsWithTag ("Player").transform.position;
Xdif = Player.x - transform.position.x;
Ydif = Player.y - transform.position.y;
playerDirection = new Vector2 (Xdif, Ydif);
if (!Physics2D.Raycast (transform.position, playerDirection, 5, Wall)) {
GetComponent<Rigidbody2D>().AddForce (playerDirection.normalized * speed);
}
}
}
The issue is that FindGameObjectsWithTag
returns an array, in this case of all objects tagged Player. As the error says a GameObject array doesn't contain a Transform. Each item within it does but the array itself does not.
If you only have one player gameobject then use FindWithTag ins$$anonymous$$d. You should also cache the reference to the player at start rather than finding it every frame. If you have multiple player objects then the enemy will need to choose one from that array.