How do you get an int from a prefab?

238 views Asked by At

I have a prefab of a store. This store has a count integer in it to signify how many things the store is holding. But this prefab populates many stores with different int values. So store one could have 3 items while store 2 has 40 items and so forth. I need a way to add all of those up and use it in another script. I don't even know where to start. An answer would be ideal but if not just a nudge in the right direction would be greatly appreciated. Thank you in advance.

1

There are 1 answers

2
TEEBQNE On BEST ANSWER
int storeSum = 0;

foreach (YourScriptHere store in FindObjectsOfTypeAll(typeof(YourScriptHere)) as YourScriptHere[])
{
    storeSum += store.theValueHere;
}

Fill in the YourScriptHere with the class name of the script you are trying to find. It will grab all occurrences of the prefab in the scene then add the value you have set. Replace the theValueHere with whatever the integer field you have setup. If you are looking to add up editor objects, that is a different approach which I can edit the answer if that is the case.

The other approach is having a manager that has all references to each of these objects so you do not need to call FindObjectsOfTypeAll. If these values change during runtime and you want to recalculate it, I would either assign the references in the inspector or store the references. In case some of these objects are destroyed or new ones are instantiated, I would consider using a HashSet when storing the references.