I’m watching a tutorial on youtube, i can’t seem to find out why this happens;
NullReferenceExceptionn: Object reference not set to an instance of an object BuildManager.get_HasMoney () (at Assets/Scripts/BuildManager.cs:30)
thats the compile error i get inside Unity^^. I’m making a turret game, for practising. my Nodes, where i can build my turrets by first clicking on a turret image, and than hover over a node to buy and build. if i don’t have enough money for this, the Node is supposed to highlight red, this does not happen. If i have enough money it’s supposed to highlight green, which also does not happen.
This is not when the compile error happens though, it happens whenever i hover my mouse over a node, Before selecting any turrets.
deeply appreciate if someone helps, if you need more information, tell me.
We need your script to help you find the problem.
This very common error is telling you that you are trying to call your function .get_HasMoney () from a null object.
Did you initialize your BuildManager. properly ?
1 Like
that’s what i’ve been trying to do, and i thought i had done it right
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BuildManager : MonoBehaviour {
public static BuildManager instance;
private void Awake()
{
if (instance != null)
{
Debug.Log(“More than one BuildManager in scene!”);
}
instance = this;
}
public GameObject buildEffect;
private TurretBlueprint turretToBuild;
private Node selectedNode;
public NodeUI nodeUI;
public bool CanBuild { get { return turretToBuild != null; } }
public bool HasMoney { get { return PlayerStats.Money >= turretToBuild.cost; } }
public void SelectNode (Node node)
{
if (selectedNode == node)
{
DeselectNode();
return;
}
selectedNode = node;
turretToBuild = null;
nodeUI.SetTarget(node);
}
public void DeselectNode()
{
selectedNode = null;
nodeUI.Hide();
}
public void SelectTurretToBuild (TurretBlueprint turret)
{
turretToBuild = turret;
selectedNode = null;
DeselectNode();
}
public TurretBlueprint GetTurretToBuild()
{
return turretToBuild;
}
}
this is the code from that class
Are you able to call sucessfully your BuildManager from other script ?
How many scene have you ? Are you calling your buildManager from the same scene it has been created ? (otherwise you need to call "DontDestroyOnLoad(gameObject);"in your “Awake” function in the BuildManager script.
Another possibility would be that the things you are calling in this function
public bool HasMoney { get { return PlayerStats.Money >= turretToBuild.cost; } }
are the null object which are throwing the error.
So i suggest you to add something like
“public bool test” as a parameter of the BuildManager class, and try to access it with “BuildManager.instance.test” from another script. The result should help you find the error
1 Like
it’s correct, that’s the line that causes the problem, sorry i forgot to mention that, was quite important… i only have one scene. I’m very new to this, it’s a youtube tutorial i found, i have learnt alot but there is still much i don’t understand. which is for exmaple this error^^
not 100% sure what you are talking about, is it right that i have not accessed that code from somewhere else? is that what instance means?
also not 100% sure how to test this with ¨public bool test¨
you want me to create ¨public bool test;¨ in the GameManager, and try to access it from another script?
So let says that this is your buildmanager :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TEST : MonoBehaviour {
public static TEST instance = null;
public bool isItThrowingAnError;
void Awake()
{
//Check if instance already exists
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject); //Keep this object when loading a new scene
}
}
You should be able to access the boolean in another script by doing :
Debug.Log(TEST.instance.isItThrowingAnError);
Oh and an important detail:
this script “TEST” should exist in the scene (So does your BuildManager). So make sure to add your script to a gameobject
1 Like
can’t access it… thanks alot for trying but now i am a bit lost… i will try more tomorrow i guess.
tried to copy what you wrote, i couldn’t access from another script
If your BuildManager script is attached to a gameobject of your scene, you should be able to access his properties and call his method from another script by calling “BuildManager.instance.yourMethod…”
this is the purpose of having a static instance of your class.
Now if you are having the error " Object reference not set to an instance of an object" when trying to call “BuildManager.instance…” It probably means that your BuildManager script is not present in the scene.
So just drag and drop your buildManager script onto a gameobject of your scene, and hit play. If the error persist, we should investigate more
i have an Empty object where i store these scripts, so not sure if that’s the problem. I have searched if there are objects that miss scripts but didn’t find anything.
also found this error
NullReferenceException: Object reference not set to an instance of an object
BuildManager.get_HasMoney () (at Assets/Scripts/BuildManager.cs:32)
Node.OnMouseEnter () (at Assets/Scripts/Node.cs:116)
UnityEngine.SendMouseEvents: DoSendMouseEvents(Int32)
FOUND THE MISTAKE, it’s a common mistake i think among us starters. instead if a small letter on a method, i used capital. thanks for your help anyways! stay tuned tho, i know where to come if i need any more help:p
I have the same problem even if I try to access it from the same script.
NullReferenceException: Object reference not set to an instance of an object
BuildManager.get_HasMoney () (at Assets/Scripts/BuildManager.cs:41)
BuildManager.Update () (at Assets/Scripts/BuildManager.cs:46)
Here is my code"
using UnityEngine;
public class BuildManager : MonoBehaviour {
public static BuildManager instance;
private void Awake()
{
//if (instance != null)
//{
// Debug.Log("More than one BuildManager in scene!");
// return;
//}
//instance = this;
//Check if instance already exists
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject); //Keep this object when loading a new scene
}
[Header("Nodes")]
public GameObject nodes;
[Header("Turret Prefabs")]
public GameObject knifeTurretPrefab;
public GameObject knifeRange;
public GameObject spearTurretPrefab;
public GameObject spearRange;
private TurretBlueprint turretToBuild;
private GameObject currentTurretRange;
[HideInInspector]
public Transform currentTurret;
public bool CanBuild { get { return turretToBuild != null; } }
public bool HasMoney { get { return PlayerStats.Money >= turretToBuild.cost; } }
private void Update()
{
Debug.Log(HasMoney.ToString());
if (currentTurret != null)
{
Vector3 m = Input.mousePosition;
m = new Vector3(m.x, m.y, transform.position.y);
Vector3 p = Camera.main.ScreenToWorldPoint(m);
currentTurret.position = new Vector3(p.x, p.y, p.z);
}
if (Input.GetMouseButtonDown(0) && currentTurret != null)
{
Destroy(currentTurret.gameObject);
}
}
public void SelectTurretToBuild(TurretBlueprint turret, GameObject range)
{
turretToBuild = turret;
currentTurretRange = range;
nodes.SetActive(true);
currentTurret = ((GameObject)Instantiate(turretToBuild.prefab)).transform;
ChangeRangeMat changeRangeMat = (ChangeRangeMat)FindObjectOfType(typeof(ChangeRangeMat));
changeRangeMat.RangeMatRed();
currentTurretRange.SetActive(true);
currentTurret.GetComponent<Turret>().range = 0f;
}
public void BuildTurretOn(Node node)
{
//Build a turret
if(PlayerStats.Money < turretToBuild.cost)
{
Debug.Log("Not enough money to build that!");
return;
}
if (currentTurret != null)
{
PlayerStats.Money -= turretToBuild.cost;
GameObject turret = (GameObject)Instantiate(turretToBuild.prefab, node.GetBuildPosition(), Quaternion.identity);
node.turret = turret;
Destroy(currentTurret.gameObject);
node.turret.transform.GetChild(0).gameObject.SetActive(false);
BoughtTurret();
Debug.Log("Turret build! Money left: " + PlayerStats.Money);
}
}
public void BoughtTurret()
{
turretToBuild = null;
currentTurret = null;
nodes.SetActive(false);
//currentTurretRange.SetActive(false);
currentTurretRange = null;
}
}
Everything work fine except line 41 which return null.
Check if PlayerStats or turretToBuild is null, check via Debug.Log. On that note, where are you defining PlayerStats?
Thank you for your reply. Indeed turretToBuild was null and that’s the reason I get null reference. I changed the script and now it work fine.
what I am doing wrong in this scripts that I get
NullReferenceException: Object reference not set to an instance of an object
TurretUI.SetTarget (UnityEngine.GameObject _target) (at Assets/Scripts/TurretUI.cs:49)
BuildManager.SelectTurret (UnityEngine.GameObject turret) (at Assets/Scripts/BuildManager.cs:90)
Turret.OnMouseDown () (at Assets/Scripts/Turret.cs:77)
UnityEngine.SendMouseEvents:smile:oSendMouseEvents(Int32) ?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TurretUI : MonoBehaviour {
public GameObject ui;
private GameObject target;
[HideInInspector]
public Node node;
[HideInInspector]
public Turret turret;
[HideInInspector]
public TurretBlueprint turretBlueprint;
[Header("Buttons and Text")]
public Text turretNameText;
public Button sellButton;
public Text sellText;
public Button upgradeButton;
public Text upgradeText;
public Button nearestTargetButton;
public Button weakestTargetButton;
public Button strongestTargetButton;
public Button BersekerButton;
private void Start()
{
//Debug.Log(node.isUpgradedL2);
node = gameObject.GetComponent<Node>();
turret = GetComponent<Turret>();
turretBlueprint = GetComponent<TurretBlueprint>();
}
public void SetTarget(GameObject _target)
{
target = _target;
//Move the UI
//transform.position = target.GetBuildPosition();
target.gameObject.layer = LayerMask.NameToLayer("TurretImage");
target.transform.GetChild(2).gameObject.layer = LayerMask.NameToLayer("TurretImage");
target.transform.GetChild(0).gameObject.SetActive(true);
target.transform.GetChild(1).gameObject.SetActive(true);;
if (node.isUpgradedL2 == false)
{
turretNameText.text = turretBlueprint.l1TurretName;
}
else if(node.isUpgradedL3 == false)
{
turretNameText.text = turretBlueprint.l2TurretName;
}
else if(node.isUpgradedL3 == true)
{
turretNameText.text = turretBlueprint.l3TurretName;
}
ui.SetActive(true);
}
public void Hide(GameObject target)
{
if(target != null)
{
target.gameObject.layer = LayerMask.NameToLayer("Default");
target.transform.GetChild(2).gameObject.layer = LayerMask.NameToLayer("Default");
target.transform.GetChild(0).gameObject.SetActive(false);
target.transform.GetChild(1).gameObject.SetActive(false);
}
ui.SetActive(false);
}
public void Upgrade()
{
node.transform.position = node.GetBuildPosition();
node.UpgradeTurret();
BuildManager.instance.DeselectTurret(target);
}
}
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Node : MonoBehaviour {
[Header("Hover Color")]
public Color hoverColor;
[HideInInspector]
public GameObject turret;
[HideInInspector]
public TurretBlueprint turretBlueprint;
[HideInInspector]
public bool isUpgradedL2 = false;
[HideInInspector]
public bool isUpgradedL3 = false;
private Renderer rend;
private Color startColor;
private ChangeRangeMat changeRangeMat;
//private TurretOptions turretOptions;
//[Header("Text")]
//public Text turretNameText;
//public Text upgradeText;
//public Text sellText;
BuildManager buildManager;
private void Start()
{
rend = GetComponent<Renderer>();
startColor = rend.material.color;
buildManager = BuildManager.instance;
}
public Vector3 GetBuildPosition()
{
return transform.position;
}
private void OnMouseDown()
{
if(EventSystem.current.IsPointerOverGameObject())
{
return;
}
if (!buildManager.CanBuild)
{
return;
}
if (turret != null)
{
Debug.Log("Can't build here!");
return;
}
BuildTurret(buildManager.GetTurretToBuild());
}
void BuildTurret(TurretBlueprint blueprint)
{
//Build a turret
if (PlayerStats.Money < blueprint.cost)
{
Debug.Log("Not enough money to build that!");
return;
}
if (blueprint != null && buildManager.CanBuild)
{
PlayerStats.Money -= blueprint.cost;
GameObject _turret = (GameObject)Instantiate(blueprint.prefab, GetBuildPosition(), Quaternion.identity);
turret = _turret;
turretBlueprint = blueprint;
GameObject effect = (GameObject)Instantiate(buildManager.buildEffect, GetBuildPosition(), Quaternion.identity);
Destroy(effect, 5f);
Destroy(buildManager.currentTurret.gameObject);
turret.transform.GetChild(0).gameObject.SetActive(false);
turret.transform.GetChild(1).gameObject.SetActive(false);
BoxCollider bC = turret.AddComponent<BoxCollider>();
bC.size = new Vector3(2, 34, 2);
//Debug.Log(turretBlueprint.l1TurretName);
//turretOptions.turretNameText.text = turretBlueprint.l1TurretName;
//upgradeText.text = "Upgrade: " + turretBlueprint.upgradeCostL2;
buildManager.BoughtTurret();
//Debug.Log("Turret build!");
}
}
public void UpgradeTurret()
{
//Upgrade a turret
if (isUpgradedL2 == false)
{
if (PlayerStats.Money < turretBlueprint.upgradeCostL2)
{
Debug.Log("Not enough money to upgrade that!");
return;
}
if (turretBlueprint != null && buildManager.CanBuild)
{
PlayerStats.Money -= turretBlueprint.upgradeCostL2;
//Get rid of the old turret
Destroy(turret);
//Build a new one
GameObject _turret = (GameObject)Instantiate(turretBlueprint.upgradePrefabL2, GetBuildPosition(), Quaternion.identity);
turret = _turret;
GameObject effect = (GameObject)Instantiate(buildManager.buildEffect, GetBuildPosition(), Quaternion.identity);
Destroy(effect, 5f);
Destroy(buildManager.currentTurret.gameObject);
turret.transform.GetChild(0).gameObject.SetActive(false);
turret.transform.GetChild(1).gameObject.SetActive(false);
BoxCollider bC = turret.AddComponent<BoxCollider>();
bC.size = new Vector3(2, 34, 2);
//turretNameText.text = turretBlueprint.l2TurretName;
//upgradeText.text = "Upgrade: " + turretBlueprint.upgradeCostL3;
buildManager.BoughtTurret();
isUpgradedL2 = true;
}
}
else if (isUpgradedL2 == true && isUpgradedL3 == false)
{
if (PlayerStats.Money < turretBlueprint.upgradeCostL3)
{
Debug.Log("Not enough money to upgrade that!");
return;
}
if (turretBlueprint != null && buildManager.CanBuild)
{
PlayerStats.Money -= turretBlueprint.upgradeCostL3;
//Get rid of the old turret
Destroy(turret);
//Build a new one
GameObject _turret = (GameObject)Instantiate(turretBlueprint.upgradePrefabL3, GetBuildPosition(), Quaternion.identity);
turret = _turret;
GameObject effect = (GameObject)Instantiate(buildManager.buildEffect, GetBuildPosition(), Quaternion.identity);
Destroy(effect, 5f);
Destroy(buildManager.currentTurret.gameObject);
turret.transform.GetChild(0).gameObject.SetActive(false);
turret.transform.GetChild(1).gameObject.SetActive(false);
BoxCollider bC = turret.AddComponent<BoxCollider>();
bC.size = new Vector3(2, 34, 2);
//turretNameText.text = turretBlueprint.l3TurretName;
//upgradeText.text = "LEVEL MAX";
buildManager.BoughtTurret();
isUpgradedL3 = true;
}
else if (isUpgradedL2 == true && isUpgradedL3 == true)
{
Debug.Log("Max Level!");
}
}
Debug.Log("Turret upgraded!");
}
private void OnMouseEnter()
{
if(EventSystem.current.IsPointerOverGameObject())
{
return;
}
if (!buildManager.CanBuild)
{
return;
}
if (turret != null)
{
changeRangeMat = (ChangeRangeMat)FindObjectOfType(typeof(ChangeRangeMat));
changeRangeMat.RangeMatRed();
return;
}
else
{
rend.material.color = hoverColor;
if (buildManager.currentTurret != null)
{
changeRangeMat = (ChangeRangeMat)FindObjectOfType(typeof(ChangeRangeMat));
changeRangeMat.RangeMatWhite();
}
}
}
private void OnMouseExit()
{
if (buildManager.currentTurret != null)
{
rend.material.color = startColor;
changeRangeMat = (ChangeRangeMat)FindObjectOfType(typeof(ChangeRangeMat));
changeRangeMat.RangeMatRed();
}
}
}
I solved by moving all the upgrade stuff in to the turret script and changed the references from GameObject to Turret