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?

If you're interested, you can read the rules for Unity Answers, in the FAQ. And also the sticky at the top of the newer Help Room.

–

1 Answer

1

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);