- Home /
Attack player script not working?
i am making a zombie game, but i keep getting an error about an object not set, and wont add the damage to the player. her is the error:
NullReferenceException: Object reference not set to an instance of an object ZombieAttack.Update () (at Assets/Scripts/Zombie/ZombieAttack.cs:22)
but it is assigned and working like it should, exept for the health going down.
here is the code attached to the player:
using UnityEngine;
using System.Collections;
public class ZombieAttack : MonoBehaviour
{
public GameObject[] enemies;
LifeScript life;
void Start()
{
life = GetComponent<LifeScript>();
enemies = GameObject.FindGameObjectsWithTag("zombie");
}
void Update()
{
enemies = GameObject.FindGameObjectsWithTag("zombie");
for (int i = 0; i < enemies.Length; i++)
{
Debug.Log(i);
if (enemies[i].GetComponent<ZombieWalking>().canAttack == true)
{
life.health -= enemies[i].GetComponent<ZombieWalking>().dam;
enemies[i].GetComponent<ZombieWalking>().canAttack = false;
}
}
}
}
and here is the code the script is referencing on the zombie:
using UnityEngine;
using System.Collections;
public class ZombieWalking : MonoBehaviour {
public float speed;
public GameObject player;
public float distanceToPlayer;
public float cooldown;
public bool canAttack = false;
public int dam = 6;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag ("rick");
}
// Update is called once per frame
void Update () {
distanceToPlayer = Vector3.Distance (transform.position, player.transform.position);
if (distanceToPlayer > 1.6f && distanceToPlayer < 10.0f) {
transform.position = Vector3.MoveTowards (transform.position, player.transform.position, speed);
transform.LookAt(player.transform.position);
}
if (distanceToPlayer < 2)
{
if (!canAttack)
{
cooldown -= Time.deltaTime;
if (cooldown < 0.1f)
{
canAttack = true;
cooldown = 3;
}
}
}
if (distanceToPlayer > 2)
{
canAttack = false;
cooldown = 3;
}
}
}
please help if you can :(
Answer by malkere · Jul 03, 2015 at 02:24 PM
null reference means its null. at 22 that means your player is null. that means your find tag is not working. Should it be "Rick" and not "rick"? or something like that. add a debug before the look at to see what player.gameObject.name returns as (should be null) then pause and look at the player during runtime to see what his tag looks like. should be a silly mistake you'll notice if you look closer.
one of the script names changed, and i forgot to change it in the scripts. still allot of thanks for helping, i did find a wrong tag.
Your answer
Follow this Question
Related Questions
Zombie script 1 Answer
how to make an AI damage a third person controller ? 1 Answer
How do I get my zombie, to attack my 3rd person controller? 0 Answers
Zombie Alien Mellee Attack 1 Answer
Attack Script problem please help 1 Answer