So I have created a player health script it works great with enemy’s that i hand put in the game if I collide with an enemy or if it shoots me I loose health but when I use my spawner to spawn random enemy’s and I collide with and enemy I am getting a NullReferanceException taking me to this.
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
public int number;
public Transform Powerup_speedBouns;
public Transform Powerup_shield;
public int attackDamage = 10;
public GameObject Player;
public PlayerHealth playerHealth;
void Attack()
{
if (playerHealth.currentHealth > 0) ///Here///
{
playerHealth.TakeDamage(attackDamage);
}
}
}
I noticed that in my prefab for my enemy I am not allowed to my player to playerHealth in the inspector which is why I am getting the error, but I can when it is in the scene, what am I doing wrong?
Here is my full script if it helps any.
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour
{
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
public int number;
public Transform Powerup_speedBouns;
public Transform Powerup_shield;
public int attackDamage = 10;
public GameObject Player;
public PlayerHealth playerHealth;
private GameController gameController;
void Start()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Boundary") || other.CompareTag("Enemy"))
{
return;
}
if (explosion != null)
{
Instantiate(explosion, transform.position, transform.rotation);
number = Random.Range(1, 50);
Debug.Log(number);
if (number == 1)
Instantiate(Powerup_speedBouns, transform.position, Quaternion.identity);
number = Random.Range(1, 50);
if (number == 1)
Instantiate(Powerup_shield, transform.position, Quaternion.identity);
}
if (other.tag == "Player")
{
Attack();
}
if (playerHealth.currentHealth <= 0)
{
Instantiate(playerExplosion, transform.position, transform.rotation);
gameController.GameOver();
Destroy(gameObject);
}
gameController.AddScore(scoreValue);
Destroy(gameObject);
}
void Attack()
{
// If the player has health to lose...
if (playerHealth.currentHealth > 0)
{
// ... damage the player.
playerHealth.TakeDamage(attackDamage);
}
}
}