- Home /
Enemy Respawn causes player to unable to attack
Ok so when i attack and kill the enemy it respawns back to its starting position the only problem is im unable to fight it again i get this error
missingreferenceexception: the object of type 'gameobject' has been destroyed but you are still trying to Access it your script should either check if it is null or you should not destroy the object.
what is my problem?
here is the player attack script
using System.Collections;
public class PlayerAttack : MonoBehaviour { public static GameObject target; public float attackTimer; public float Cooldown;
void Awake(){
target = GameObject.FindGameObjectWithTag("Enemy");
}
// Use this for initialization
void Start () {
attackTimer = 0;
Cooldown = 1.0f;
}
// Update is called once per frame
void Update () {
if(attackTimer > 0)
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
attackTimer = 0;
if(Input.GetKeyUp(KeyCode.Mouse0)){
if(attackTimer == 0){
Attack();
attackTimer = Cooldown;
}
}
}
private void Attack(){
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
Debug.Log(direction);
if(distance < 2.5f){
if(direction > 0){
EnemyHealth Health = (EnemyHealth)target.GetComponent("EnemyHealth");
Health.AdjustCurrentHealth(-10);
}
}
}
}
when you destroy
the enemy object do you reacquire it, or do you continue to use the same reference?
Answer by Sirex · May 20, 2012 at 08:41 PM
Here is the problem, it gets destroyed then you don't reasing target to the new enemy gameobject.
void Awake(){
target = GameObject.FindGameObjectWithTag("Enemy");
}
The solution is a design decision. I will give two alternatives.
Refactor our the above statement to a updateTarget function and make a raycast detect code that you call in the players update function and reset target.
Declare target as a property and have it set by the enemy script in the enemy script start function. You can access it from the player script by some find gameobject code, or make the variable static.