Global Scripts/Variables

Hi, I’m creating a game with multiple levels. I’m trying to grab the native Resolution of the screen my game is running on and store it. Then use this native resolution value and divide by the current resolution to get a ratio. (This way I can scale things, mainly my GUI for different resolutions)

(Feel free to suggest other ways to do this but ultimately I would like to learn how/if it’s possible to have global scripts that work on every level)

Thanks in advance


The way I’m currently doing this is creating an Empty game object and attaching a script, on Start() I use DontDestroyOnLoad(gameObject); However this causes some issues with null values in my script :frowning:

Yes, it is possible to have global scripts that work on every level.

You can add static methods to any class that you define. These methods don’t need an instance of the object to be called. You would call something like “MyClass.getScreenRatio” instead of someObject.getScreenRatio.

The trick there is that you want it to work regardless of which scene is loaded first. But this isn’t hard, you just need to initialize it the first time it is used if it hasn’t been initialized yet.

private static Vector2 screenRatio = null;
public static Vector2 getScreenRatio()
    if (screenRatio == null) {
        screenRatio = // do calculation here
    return screenRatio;

As for your original trick (empty game object, DontDestroyOnLoad) that can be made to work. You were getting null errors but I suspect those could be solved with a similar trick to the one I showed above, to guarantee that something is initialized the first time it is accessed.

This game object approach has a very compelling feature, which is that the object will get all the Unity calls (OnUpdate, etc.) However there is a major problem with that strategy, which is that it requires you always have to run your game starting from the level that defines the empty game object. You couldn’t debug a different scene in the Unity editor, for instance. So then you end up adding the same empty game object to multiple levels, but then every time you switch scenes you get another one.

What you’d want is a game object that always is around, but there is always exactly one of them, no more, no less. This problem is called a Singleton. Here’s a good discussion of ways to do them in Unity: