Hi guys, I keep receiving this:
NullReferenceException: Object reference not set to an instance of an object
DestroyByContact.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scritps/DestroyByContact.cs:41)
What I am trying to do is to give my player some Health (PlayerHealthAndDmg is Player script)
And allow enemies to provide dmg to player when collision happends (DestroyByContact is attached to Enemy)
I am kinda new to whole game making and programing, so be gentle please
Thanks!
Here is code:
using UnityEngine;
using System.Collections;
public class PlayerHealthAndDmg : MonoBehaviour {
public int playerHealth;
public int playerDamage;
void Start ()
{
playerHealth=10;
}
public void UpdatePlayerHealth (int pUdt){
playerHealth = playerHealth + pUdt;
}
public int GetPlayerHealth (){
return playerHealth;
}
}
And second file:
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour {
public GameObject explosion;
public GameObject explosionPlayer;
public int scoreValue;
private GameController gameController;
private PlayerHealthAndDmg playerHealthAndDmg;
void Start()
{
GameObject gameControllerObject = GameObject.FindGameObjectWithTag ("GameController");
if (gameControllerObject != null) {
gameController = gameControllerObject.GetComponent<GameController> ();
}
if (gameControllerObject == null) {
Debug.Log ("Cannot find 'GameController' script");
}
GameObject playerHealthAndDmgObject = GameObject.FindGameObjectWithTag ("Player");
if (playerHealthAndDmg != null) {
playerHealthAndDmg = playerHealthAndDmgObject.GetComponent<PlayerHealthAndDmg> ();
}
if (playerHealthAndDmg == null) {
Debug.Log ("Cannot find 'Player' script");
}
}
void OnTriggerEnter(Collider other) {
if (other.tag == "Boundry")
return;
if(other.tag =="Enemy")
return;
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player") {
playerHealthAndDmg.UpdatePlayerHealth(-10);
if(playerHealthAndDmg.GetPlayerHealth()<0)
Instantiate (explosionPlayer, other.transform.position, other.transform.rotation);
gameController.GameOver ();
}
gameController.AddScore (scoreValue);
Destroy(other.gameObject);
Destroy (gameObject);
}
}