It’s fine for me to get its value to existed in scene objects with getComponent in Start(). But when I need these values in initiated objects I can’t access them simply because the object, where these values in, disabled by the time I instantiate another object, where I need these values. I hope it’s not too confusing, mb some code will help to understand.
object where I need this value:
void Start()
{
house = GameObject.Find(“HousingPanel”).GetComponent(); // this line is
wrong for an initiated object
}
void Update()
{
if (score.i <= house.capacity) // score object is fine, cos it isn't disabled
// some code
}
object where they store:
public class housingPanelScript : MonoBehaviour
{
public int capacity = 10;
//some code
public void upgradeHouse()
{
capacity += 10;
}
}
First, it’s bad practice to use “Find”, you should set up a reference that’s more reliable/safe.
You can either not disable it, instead move it off the screen or if it’s a UI element use Canvas Group to make it inactive/invisible. Then you could still access the value
Your other option is to have some script somewhere that you can save the data to, then you can access it from that place instead (provided that it’s a value type not reference).
Alternatively, if it’s just the score maybe you could consider using PlayerPrefs.SaveInt or SaveFloat. Give it a name and the value to save, then load it out using the same name you gave it when you saved it. Bear in mind, this will save it in memory. So when you restart your game, that value will be saved. This might be useful if you want the score to be persistent and use it have a high score or something… Otherwise you could do PlayerPrefs.DeleteAll on start, but to be honest it’s probably not what you want if you intend to reset the score every play. It’s just an option to consider.