getting static vars from other scenes?

hi i was just wondering if it is possible to access static vars from other scripts in other scenes? because i am making a game where you can buy weapons and then use them in different levels but all of that is in different scenes so i dont know how to access the money vars in the different scenes. at first i tried `DontDestroyOnLoad()`

but that didn’t work because when you went back to the first scene it made two versions of the object.

Static variables only get created once across all objects, so even though you have 2 instances of the same object, the static variable declared inside that object is shared between both instances of the object. E.G.

// This is our class
public class SomeClass : MonoBehaviour
{
    // This is our static variable
    public static float someFloat = 10.0f;
}

someFloat will be the same no matter where you access it from E.G.

// Another class
public class OtherClass : MonoBehaviour
{
    void Update()
    {
        // Print someFloat to the debug log
        Debug.Log(SomeClass.someFloat.ToString());
    }
}

So your instances of the class shouldn't change. Now whether Unity resets the static variable on loading another scene I'm not sure, but what you can do is set it up like a Singleton, by checking if there is another copy of the class in the scene like so.

// This is our class
public class SomeClass : MonoBehaviour
{
    // This is our static variable
    public static float someFloat = 10.0f;
    // Variable to store a reference to class
    private static SomeClass instance;

    void Awake()
    {
        if(instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this);
        }
    }
}

What this does is stores a reference to itself inside a static variable that is shared across all instances of the class, and in Awake(), checks to see if there is already a copy of itself in the static variable. If there is, then it destroys itself, otherwise it places itself in there. By using DontDestroyOnLoad() on this object, you will only have one copy in any scene you load, and will remain the same object throughout.

You can only access objects in the current scene. DontDestroyOnLoad is correct; in order to prevent more than one copy, you can either have it on a script in a scene that's executed once only (like a splash screen), or else detect in the Awake function if another copy already exists, in which case destroy itself.