Singleton using variables from gameobjects in another scene, from the get go. How to approach?

Hi guys

I’m making a game involving multiple scenes and resources. While some resources can only be gained and spent by building buildings in specific scenes, I need the resource counter to keep increasing no matter what scene you’re in.
I asked for help on the forums and gotten some great feedback, but a new challenge has emerged.

Currently my situation is that I have the object containing the resources (and their amount) as a singleton, loaded in the start scene.
To calculate the resource income I do however need to make use of an array refering to the objects with my buildingMananger-script attached, and for some resources these are placed in other scenes, meaning that I can’t reference them from the getgo, which result in them not being implemented to the singleton resourceManager at all.

I thought about making the buildingManager-script static, which should allow me to reference them in the singleton array in located in scene 1, but I cant figure out how to make arrays work in static classes.
I guess another option would be to make all the buildings singletons placed in the first scene, but that appears to be even more cpu/memory heavy to me.
Either way I’m not convinced that any of the two options are the best approach. I keep reading warnings about too many statics/singletons, and this would result in a lot of extra statics or singletons depending on the solution.

Now I’m halfway to a solution that requires neither, were a resourcePerSec singleton recieves the building data, once entering the relevant scene, but that would create the another problem when loading the game, if I understand the function correctly.
In this case if the player had saved the game and closed the game, while having enough buildings to give a +10/sec bonus of a specific resource in scene 3, wouldnt that bonus first activate once re-entering the scene once more after loading?

I hope the overall problem is clear, but if not I will elaborate further :slight_smile:

What would you consider the best solution for a scenario like this?

Thank you for reading

ps. In case anyone are becomming annoyed by my stream of questions regarding singletons, dontdestroyonload, statics and other related topics, please bear with me. This is a pretty abstract concept to me, but so far the community has been such a great help so far in helping me understand it :slight_smile:

Can you post the code you’ve tried with this, and elaborate on what’s giving you trouble? Arrays aren’t special with regard to static and instanced members, so they ought to work the same. The only exception that comes to mind is that you can’t (without some trouble) edit the contents of a static array in the inspector, so if you’ve relied on the inspector to populate the array, I can see how that would be new.

I’d say focus on the nuts&bolts. Look for tricks you can use and ignore the high-concept stuff.

Putting a gameManager script on an gameObject in a set-up scene is a nice trick – can use the Inspector is nice, and Unity will 100% create it and run Awake on it for you, first thing. Using static public managerScript MS; so everyone in any scene can find it is nice. It works better than gameObject.Find(“nameIalwaysSpellWrong”) in each scene.

Maybe that’s called a Singleton, maybe it’s not. Maybe it’s technically one change away from being one. Maybe my pants would officially be trousers if I sewed just pocket shut. Unless your teacher is grading you on proper use of Singletons, and you need the points, who cares?

As far as advice you see, ignore it unless someone can back it up. Someone says too many statics can cause problems? Suppose someone told you drinking straws can cause problems with babies. OK, but is it dangerous for eye-pokes, or messy, or takes longer, or do they have a rant about how it causes autism? You wouldn’t just say “yes, random stranger, I’m throwing away all my straws now.”

Making the building stats globals, created in the first scene (what it looks like you might be asking about) is a common trick. Then a real Inn just needs to have it’s location, current health, upgrade level, and a pointer back to the Inn blueprint (size, max health, production rates.) But it makes the program more complicated. It’s simpler to just have an Inn prefab will all the stats in it. Sure, each Inn you instantiate will uselessly have a copy of the same basic stats, wasting space, but not enough to matter.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class BuildingManagerWood : MonoBehaviour {

    public UnityEngine.UI.Text buildingInfo;
    public WoodManager woodManager;
    public string buildingName;
    public double woodsmenBoost;
    public double count;
    public double cost;
    public double coefficient;
    private double baseCost;


    void Start ()
    {
     baseCost = cost;            
    }   
     
    void Update ()
    {
        buildingInfo.text = "Lvl " + count + " " + buildingName;
     }


    public void PurchasedBuilding ()
    {
    if (woodManager.wood >= cost)
    {
    woodManager.wood -= cost;
    count += 1;
    cost = Mathf.Round((float)baseCost * Mathf.Pow((float)coefficient, (float)count));
    }
    }

}

This is an old example of a building manager I wrote.
Now how would I go on to make this static, so that I could refer to the buildings with this script, using my singleton placed in my starting scene??
Before I tried out the whole multiple scenes aspect I just used “BuildingManagerWood[ ] buildings;” but as far as I can tell I can’t make the entire class static (monobehaviour can’t be static?) so what do I do instead?

I’m still very inexperienced in programming so I’m not sure if a “gameManager script” is a specific script or just something controlling a certain aspect of the game like the “resourceManager” I created that simply is the script keeping track of how many resources the player has.
I also dont know about “Static public managerScript MS;” or “building_stats_global”.
What I mean is that I dont know what is just example names and what’s actual code/commands (do the MS-part do anything for instance? :stuck_out_tongue: )

But true… you learn alot by trial and error and I try to do so most of the time, but with coding it seems like there really are some “wrong” and “right” ways in some aspects of it :slight_smile:

It’s possible to make a (non-MonoBehaviour) class static, but that is emphatically not what you want. You need the instances, all you need to do is to add a way to get a list of all of them.

Enter the… I don’t know what you’d call this pattern, actually. A maintained static list, maybe? In any case, it’s like a singleton, except it gives you a list of all of them! Let’s call it a multiton! :slight_smile:

public class BuildingManagerWood : MonoBehaviour {
public static BuildingManagerWood[] all {
get {
if (_all == null) _all = new List<BuildingManagerWood>();
return _all.ToArray();
}
}
private static List<BuildingManagerWood> _all;

void Awake() {
if (_all == null) _all = new List<BuildingManagerWood>();
_all.Add(this);
}

Sounds good, but i still dont know how to call the array :-/
Normally I’d write:

//Somewhere in the beginning
public BuildingManagerWood[] buildings;
//And then later in the script i'd reference the buildings by saying:
foreach (BuildingManagerWood building in buildings)

But when it’s a static I cant figure out what references to use. None of the guesses I’m making seems to be correct.
Also in your example: At what point do we define what _all is?

In this case it’d be

foreach (BuildingWoodManager building in BuildingWoodManager.all) {
1 Like

In both the places it’s used, if it’s null, it gets initialized.

1 Like

Thank you that worked :slight_smile:
There are still two problems though…

  1. Once I change scene the building count reset to 0. Now I tried fixing this my making the “count” and “warfarePerSec” doubles static rather than public, but then my “PerSec” script cant access the values due to protection level :-/

  2. If I change the number of buildings to 1 from the beginning my production remains unbuffed. The production bonus first kick in once I enter the scene the building is in. Which would be a rather annoying aspect in a loading process as a player.
    In my mind that aspect should work atm, since they’re both visible so I cant figure out why that is.

“public” is not the opposite of “static”. “public” is the opposite of “private” (which is implied if neither of them exist), while “static” is a separate modifier entirely. That is, you can have “public static count;” That said, from the sounds of things, would “count” be equivalent to BuildingWoodManager.all.Count? i.e. is “count” the number of buildings you have?

Sidenote, in Unity, “float” rather than “double” is the standard for floating point numbers. It’s not a big deal, but you might run into annoyance if you try to pass your variables into Unity functions and find that you have to typecast them. (And unless you’re making an orbital simulation game, you won’t need the extra precision that “double” gets you)

I’m not quite sure I follow your second question. Are you saying that you expect to have buffs from buildings that don’t exist as objects in the game?

Ah good to know!
Yeah I know… Have already had my share of aggravation with the doubles but have been able to find a solution so far…
The reason I’m using them is that the game I’m trying to build has some elements from the idle/incremental-genre (if you’re familiar with that?).
When I started on it, I did some research on how to approach it and people seemed to agree that double was the best variable, since you will end up with having REALLY big numbers…
I never really understood why you wouldn’t go with a “long” or something like that, but I just followed the common knowledge :slight_smile:

Regarding the second question, I can see how that might be a somewhat idiotic assumption :smile:
I had put it in my mind that the building would already “exist” in the other (unopened) scene with it’s static attribute, and/or that it’s values would be accessible from the getgo, but it seems like the scene needs to be loaded…
Managed to switch them to statics, which in turn made me unable to adjust their values in the inspector :smile: (which when thinking about it was to be expected, was to be anticipated)

Hmm… To me the best solution would seem to be turning all the buildings into singletons, and throw them all onto an empty object in the main scene then… That should fix all the problems - I at least hope so - and then I guess I’ll see how CPU/memory intensive that is.

Does that seem like a reasonable solution to you?

Never mind on that last comment…
I did some more thinking, and it seems like my real problem is saving values when unloading/reloading scenes…
But that seems like another topic :slight_smile:

Thank you so much for your help StarManta!
It’s helping me understanding c#/unity quite a bit and really means a lot to me :slight_smile: