I’m trying to create a very simple AI by getting an enemy game object to find the player and follow it. Although the Player is tagged with player the function FindWithTag seems to always be returning null and I cannot figure out why. I have looked around for days without finding anyone with a similar problem to mine.
My enemy controller script uses the FindWithTag to find the player game Object:
#pragma strict
public var health = 10f;
public var damage = 5f;
public var moveSpeed = 5f;
public var testPlayer : GameObject;
/*private var stats : enemyStats;*/
private var currentHealth = health;
private var player : GameObject;
private var rb : Rigidbody2D;
function start(){
/*stats = new enemyStats(health, damage);*/
if(player == null){
player = GameObject.FindWithTag("Player");
}
rb = GetComponent(Rigidbody2D);
}
function OnCollisionEnter2D (collision : Collision2D){
//Check that the player is colliding with a powerup
if(collision.gameObject.tag == "Projectile"){
Destroy(collision.gameObject);
//currentHealth -= bulletDamage;
if(currentHealth <= 0){
Destroy(gameObject);
}
}
}
function Update(){
Debug.Log(player);
Debug.Log(testPlayer.tag);
/*transform.LookAt(player.transform);*/
/*rb.AddForce(transform.forward * moveSpeed, ForceMode2D.Impulse);*/
}
The Debug.Log statements write null and Player respectively and the collision with the projectile objects works fine and the tag is detected properly. Both the player and the enemy object are instantiated by a gamecontroller, the player right at the beginning and the enemy a few seconds after. My player game object is correctly tagged with the Player tag. [93996-player-tag.png |93996]
I can’t seem to find out why the FindWithTag function is returning null.