Hey everyone, I've been trying to make it so when I click on a GameObject then it increases my health to 100.
I think i'm pretty close but it just doesn't seem to be working. I have already got it to find the scripts and everything its just when I click on my chest I get this null reference error
NullReferenceException: Object reference not set to an instance of an object
Hover.OnMouseDown () (at Assets/Hover.js:88)
UnityEngine.SendMouseEvents:DoSendMouseEvents()
This is the part of my code where I click on the chest to increase my health And there error points to this
ph.AdjustCurrentHealth(100);
This is in Hover.JS
if (!Application.isPlaying)
return;
if(ChestLooted == true) {
if (gameObject.tag == "Chest"){
if (chestclosed == false) {
animation.Play("chestclose");
chestclosed = true;
}
}
}
else if(ChestLooted == false) {
if (chestclosed == true) {
var clickedObject : GameObject = gameObject;
showGUI = true;
animation.Play("chestopen");
var ph : PlayerHealth = GetComponent("PlayerHealth");
ph.AdjustCurrentHealth(100); //THIS IS WHERE IT INCREASES MY CHARACTERS HEALTH
chestclosed = false;
ChestLooted = true;
}
}
This is my player health script. This is in CS
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
public int curHealth = 100;
public Transform spawnPoint;
public Transform player;
public float healthBarLength;
// Use this for initialization
void Start () {
healthBarLength = Screen.width / 2;
}
// Update is called once per frame
void Update () {
AdjustCurrentHealth(0);
}
void Die() {
player.transform.position = spawnPoint.transform.position;
curHealth = 100;
}
void OnGUI(){
GUI.Box(new Rect(10, 10, healthBarLength, 20), curHealth+ "/" + maxHealth);
GUI.Label(new Rect((Screen.width / 2) + 10, 10, healthBarLength, 20), "You");
}
public void AdjustCurrentHealth(int adj) {
curHealth += adj;
if(curHealth < 0){
curHealth = 0;
Die();
}
if(curHealth > maxHealth)
curHealth = maxHealth;
if(maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width / 2) * (curHealth / (float)maxHealth);
}
}
If anyone could help or tell me what I can do to fix this that would be awesome. I've gotten scripts to change variables from different script types before I just don't understand why this is not working :(
I've looked at that before but I don't really understand it to be honest. The whole getComponent confuses me since I am only just really trying to learn how to program :) Would you be able to tell me which one I would use and yes the player health in on player :)
– anon82907700What game object is 'Hover.JS' associated with?
– j_y_k