- Home /
Attacking enemy script problem
I am using this code to attack my enemeis and it works but the problem with this script is that after I kill the enemy, I destroy the gameobject in the enemy health script, and instead og targetting another enemy 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. PlayerAttack.Attack () (at Assets/Scripts/Test Script/PlayerAttack.cs:32) PlayerAttack.Update () (at Assets/Scripts/Test Script/PlayerAttack.cs:25)
since I haven't coded anything to target another enemy but there must be another way, like making it to target the game object with tag or something. Any ideas how I should do it?
using UnityEngine; using System.Collections;
public class PlayerAttack : MonoBehaviour { public GameObject target; public float attackTimer; public float coolDown;
// Use this for initialization
void Start () {
attackTimer = 0;
coolDown = 2.0f;
}
// Update is called once per frame
void Update () {
if(attackTimer > 0)
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
attackTimer = 0;
if(Input.GetButtonUp ("Fire1")) {//(KeyCode.F))
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 eh = (EnemyHealth)target.GetComponent("EnemyHealth");
eh.AdjustCurrentHealth(-10);
}
}
}
}
Your answer
Follow this Question
Related Questions
Attack/Targeting Script Issue 1 Answer
Is this the most efficient way to attack the closest enemy? 0 Answers
Enemy attack target 1 Answer
Need Help With My AI Script 1 Answer