Answer the question
In order to leave comments, you need to log in
Unity: NullReferenceException: Object reference not set to an instance of an object what's wrong?
Throws out an error. I don't even know what to do anymore. Scripts if that hang on different objects. The first on the zombies, the second on the player. You need to run the TakeDamage function in the player script from the zombie script. That's where the mistake is.
And here are two scripts.
1-Zombie Script:
using UnityEngine;
using System.Collections;
public class ZombieAttack : MonoBehaviour
{
public int zombieCol = 0;
float timer;
public float timeBetweenAttacks = 0.5f;
public int attackDamage;
HealthScript enemyHealth;
HealthCharacter playerHealth;
void Awake()
{
playerHealth = GetComponent<HealthCharacter>();
enemyHealth = GetComponent<HealthScript>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name == "Character")
{
zombieCol = 1;
}
}
void OnTriggerExit2D(Collider2D col)
{
if (col.gameObject.name == "Character")
{
zombieCol = 0;
}
}
void Update()
{
if (zombieCol == 1)
{
ZombieController move = GetComponent<ZombieController>();
move.playerSpeedForOtherScript = 0;
timer += Time.deltaTime;
if (timer > timeBetweenAttacks && enemyHealth.HP > 0)
{
Attack();
}
}
}
void Attack()
{
timer = 0f;
if (playerHealth.HP > 0)
{
playerHealth.TakeDamage(attackDamage);
}
}
}
using UnityEngine;
using System.Collections;
public class HealthCharacter : MonoBehaviour
{
public float HP;
public bool isEnemy = true;
public UISprite healthSprite;
public float attackZombieRadi;
public float timeBetweenAttack;
float timer;
public bool zombieAttack;
void Awake()
{
healthSprite.fillAmount = 1;
}
void Update()
{
timer += Time.deltaTime;
healthSprite.fillAmount = HP / 100;
if (HP <= 0)
{
healthSprite.fillAmount = 0f;
Destroy(gameObject);
}
}
public void TakeDamage (int amount)
{
HP -= amount;
}
}
Answer the question
In order to leave comments, you need to log in
I think the problem is that you have different components for different objects - for zombies you are trying to access the life script object, but this script belongs to the character, not the zombie, so playerHealth = GetComponent(); will give null.
You are trying to bind to different objects in the wrong way. One object does not need to have a reference to another character's object. But how then to reduce life? Through the event - you have OnTriggerEnter2D - here it contains a link to the object that it just collided with, and here you need to knock out lives in it:
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name == "Character")
{
var pers = col.gameObject.GetComponent<HealthCharacter>();
if (pers != null)
{
pers.TakeDamage(attackDamage);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question