- Home /
Trouble with communication between scripts
I am trying to make an FPS survival game involving a single player and a number of cloned enemies. Each enemy has a simple AI that tells it to follow the player and when in a certain radius, it "attacks", involving a boolean that says whether or not the enemy is inflicting damage.
What I want is to have the player's health script decrease health when the damage boolean is true. I have not successfully accomplished this communication. Another script I created sets a GUIText to show the health variable and the damage boolean. This is what I have:
using UnityEngine; using System.Collections; public class HUD : MonoBehaviour { private AIEnemy aiStuff; private PlayerHealth playerhealths; public float theplayerhealth=0f; public bool damaging=false; void Start () { playerhealths = GameObject.Find("Player").GetComponent<PlayerHealth>(); aiStuff = GameObject.Find("TheEnemy(Clone)").GetComponent<AIEnemy>(); } // Update is called once per frame void Update () { theplayerhealth = playerhealths.HEALTH; damaging = aiStuff.DAMAGING; print (damaging); print(theplayerhealth); guiText.text = " " + theplayerhealth + damaging; } }
... where DAMAGING is the damage bool in the AI script, titled AIEnemy. The health script is PlayerHealth, and the health float is HEALTH.
When I run this script, nothing shows up and I get an error:
NullReferenceException
UnityEngine.GameObject.GetComponent[AIEnemy] ()
HUD.Start () (at Assets/Scripts/HUD.cs:14)
I really have no idea why I get this error or why nothing is working properly. If anyone can offer any help it would be greatly appreciated.
P.S. When I try to get the component from the enemy on line 14 (line 9 here), specifying TheEnemy or TheEnemy(Clone) does not appear to change anything. I have tried this with only one enemy spawned, and with multiple, neither situation appears to change anything.
Answer by gorgoroth · Nov 25, 2013 at 10:16 PM
Okay, I now realized that I was having this issue because I was referencing the AI script with void Start (); which ran only once and was running before the enemy had even spawned; at least that is my theory. By instead having a timer that waited until the enemy had been spawned before performing a one time function that defined the connection to the enemy AI script, I was able to make this work.
Thank you to smallbit for suggesting FindWithTag, that certainly helped.
Answer by smallbit · Nov 22, 2013 at 06:24 PM
Have you checked whether when referencing to this script, "TheEnemy(Clone)" exist? Try to rather find it using tag instead of name when working with instances. Have you double checked if the name is correct (typos)?
I tried tagging the enemy prefab and using FindWithTag, but I still get an error: NullReferenceException: Object reference not set to an instance of an object HUD.Update () (at Assets/Scripts/HUD.cs:21).