Question by
freedom667 · Jan 20, 2017 at 05:20 PM ·
unity 5gameobjectfpsunity5nullreferenceexception
Grenade damage script error
i will grenade damage to enemies but when i write this code and throw the grenade i get this error. how can i fix this?
NullReferenceException: Object reference not set to an instance of an object ApplyDamage.Attack () (at Assets/ApplyDamage.cs:38)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ApplyDamage : MonoBehaviour {
int damage = 100;
private GameObject[] enemy;
EnemyHealth enemyHealth;
private bool enemyInRange;
// Use this for initialization
void Start () {
GameObject[] enemy = GameObject.FindGameObjectsWithTag ("Enemy");
foreach(GameObject enemies in enemy)
{
enemyHealth = enemies.GetComponent<EnemyHealth> ();
}
}
void OnTriggerEnter (Collider other)
{
enemyInRange = true;
}
void OnTriggerExit (Collider other)
{
enemyInRange = false;
}
// Update is called once per frame
void Update () {
if (enemyInRange) {
Attack ();
}
}
public void Attack()
{
enemyHealth.TakeDamage (damage);
}
}
Comment