NullRefrenceException - Cant find the cost
What is wrong? It cant acess the cost in TowerScript (ts) threw TowerSpot:
bm.selectedTower.GetComponent<.TowerScript>().cost
using UnityEngine;
public class TowerSpot : MonoBehaviour {
 void OnMouseUp()
 {
     Debug.Log("TowerSpot Clicked!");
     BuildingManager bm = GameObject.FindObjectOfType<BuildingManager>();
     if(bm.selectedTower != null)
     {
         ScoreManager sm = FindObjectOfType<ScoreManager>();
         //cost cant be found! FIXME!
         if(sm.money < bm.selectedTower.GetComponent<TowerScript>().cost)
         {
             Debug.Log("Not enough money");
             return;
         }
         sm.money -= bm.selectedTower.GetComponent<TowerScript>().cost;
         
         Instantiate(bm.selectedTower, transform.position, transform.rotation);
         Destroy(transform.gameObject);
     }
 }
 
               }
using UnityEngine;
public class BuildingManager : MonoBehaviour {
 public GameObject selectedTower;
 
               }
using UnityEngine;
public class TowerScript : MonoBehaviour {
 public int cost = 5;
 
               }
You may want to get the TowerScript before accessing its members, so that you're sure it exists, and that you keep for later use.
 void On$$anonymous$$ouseUp()
  {
      Debug.Log("TowerSpot Clicked!");
      Building$$anonymous$$anager bm = GameObject.FindObjectOfType<Building$$anonymous$$anager>();
      if(bm.selectedTower != null)
      {
          Score$$anonymous$$anager sm = FindObjectOfType<Score$$anonymous$$anager>();
          //cost cant be found! FIX$$anonymous$$E!
          TowerScript t = bm.selectedTower.GetComponent<TowerScript>();
          if(sm.money < t.cost)
          {
              Debug.Log("Not enough money");
              return;
          }
          sm.money -= t.cost;
          
          Instantiate(bm.selectedTower, transform.position, transform.rotation);
          Destroy(transform.gameObject);
      }
  }
 
                  I would also recommend to put that mechanic in the building manager, in a method that you simply call from anywhere.
oh, I forgot to mention, but it'd be even better I believe, if the selectedTower member was of type TowerScript.
Answer by filifjonkaren · Dec 23, 2016 at 04:40 PM
sorry for wasting your time. I found the problem and now it is working.
Your answer