- Home /
Question by
UDN_b0c2d563-dadc-47aa-8d28-4d501e887e07 · Apr 19, 2017 at 10:12 AM ·
unity 5nullreferenceexception
NullReferenceException at line . . .
So i have this code: using UnityEngine;
public class BuildManager : MonoBehaviour {
public static BuildManager instance;
void Awake()
{
if(instance != null){
Debug.LogError("more than one buildmanager in the scene");
return;
}
instance = this;
}
public GameObject standardTurretPrefab;
public GameObject missileTurretPrefab;
public GameObject turretToBuild;
public GameObject GetTurretBuild()
{
return turretToBuild;
}
public void SetTurretToBuild(GameObject turret)
{
turretToBuild = turret;
}
}
And i get an error in this script :
using UnityEngine;
public class Shop : MonoBehaviour {
BuildManager buildManager;
void Start()
{
buildManager = BuildManager.instance;
}
public void PurchaseStandardTurret()
{
Debug.Log("Standard Turret Purchased");
buildManager.SetTurretToBuild( buildManager.standardTurretPrefab);
}
public void PurchaseMissileTurret()
{
Debug.Log("Missile Turret Purchased");
buildManager.SetTurretToBuild(buildManager.missileTurretPrefab);
}
}
at line buildManager.SetTurretToBuild( buildManager.standardTurretPrefab);.
I am sure i have the prefabs set in the inspector and the scripts attached to where they need to be attached. Can you help me with this or suggest a workaround?
Comment
Answer by Ali-hatem · Apr 19, 2017 at 11:42 AM
void Awake () {
if (instance == null) {
DontDestroyOnLoad (this.gameObject);
instance = this;
}
else if (instance != this){
Destroy(gameObject);
}
}
and in class shop delete :
BuildManager buildManager;
void Start()
{
buildManager = BuildManager.instance;
}
because BuildManager class is a static no need to reference it can bee accessed directly this way :
BuildManager.instance.SetTurretToBuild( BuildManager.instance.missileTurretPrefab);