- Home /
Can't update value of var in another class
I have variable 'capacity' which is updating normally, but I can't get an updated value in another class, but initial value is there. Help me :<
public class housingPanelScript : MonoBehaviour
{
public Housing houseObj;
public TextMeshProUGUI capacity_txt;
public int capacity = 10;
void Update()
{
capacity_txt.text = "max capacity: " + capacity.ToString();
}
// some code
public void upgradeHouse()
{
capacity += 10;
Debug.Log("capacity " + capacity);
}
}
// Score is updating btw (ontriggerenter2d method)
public class Spawn : MonoBehaviour
{
public GameObject man;
int spwCount = 0;
public housingPanelScript house;
public Destroyer score;
public void spawn()
{
if (score.i < house.capacity && spwCount < house.capacity)
{
Instantiate(man, new Vector2(-1, 1), Quaternion.identity);
spwCount++;
}
else
Debug.Log("not spwn " + house.capacity + " " + score.i);
}
}
How do you call 'upgradeHouse' and are you sure the public housingPanelScript house; is assigned to the correct script instance in your scene?
Yes, value is updating (in the original class). I can see it from debug log. I'm calling this method simply through clicking on a button.
Figured it out. Deal was in a prefab. When I manually drop a housingPanelScript object to a Spawn script it started updating. But how I can assign a prefab there as long as it either started updating?
Answer by Frodo_21 · Mar 12, 2020 at 12:19 PM
As I can see it you will get a "NullReferenceException", right?
In your "Spawn" script add the "Start()" Method and than find the GameObject, where the Script is added and find the Script on this GO.
void Start()
{
house = GameObject.Find(/*Tag of GO*/).GetComponent</*Your scripts name*/>();
}
It doesn't but thanks for that tip about getcomponent, didn't know about it
Np, but it's not solveing your problem. So if I get it right: You have more than one house and want to Instatiate a $$anonymous$$an as long as there is enough space in each house?
And you want to get the capacity of a house when it's been instantiated ?
Yes, u get it right, but it solved my problem for now and worked as it should. $$anonymous$$b I need to simplify my thoughts and stay it as it is now.
Your answer
Follow this Question
Related Questions
global variable need advice 1 Answer
Difficulties Clearing/Updating A Variable 0 Answers
Scriptable object keeps referencing the objects? 1 Answer
Variable value not changhing 3 Answers
Variable value not changing (bug or i'm just an idiot?) 0 Answers