I have a ui Button called "Attack Button". I have a script called HeroBattleController attached to my Gameobject. I have an attack button set as a serialized field and the attack button object dropped on the script in the editor.
[SerializeField]
private Button AttackButton;
public void SetButtonStatus(bool status) {
AttackButton.interactable=status;
}
Trying to access that gives me the error NullReferenceException: Object reference not set to an instance of an object
I thought putting the object in the editor would allow me to access it without having to "Find" the object. Can anyone point me in the right direction?
The error is on the line
AttackButton.interactable=status;
Complete HeroBattleController script
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HeroBattleController: MonoBehaviour {
public static string SelectedHero;
[SerializeField]
private Button AttackButton;
public void SetButtonStatus(bool status) {
AttackButton.interactable=status;
}
public void HeroTouch() {
Debug.Log("Hero was touched: "+this.name);
SetButtonStatus(false);
}
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
}
HeroTouch is called via onClick from the heroprefab object.
Update: I had the herobattlecontroller script attached to two objects, the gameobject at the root of the scene and the heroprefab object. I removed it from the gameobject and only have it on the prefab. However now when I drag the attack button to the script section on the prefab it stays bold and when I run the game the attack button reference is gone. I can drag the button to the running object and it functions as I expected. I'm clearly missing something on the connection between the object hierarchy and where the objects are usable. Putting the hero battle controller script on the root gameobject only acts the same way meaning it's bold and when ran it's missing the link.
hierarchy during edit
hierarchy during runtime



Buttonto to theAttackButtonslot from the Editor. If doing this did not fix your problem, explain how you are calling theSetButtonStatusfunction. Edit your question and put the complete script inHeroBattleController. Also, put a complete script of where you are calling theSetButtonStatusfunction from. This will help determine the problem. - Programmer