How could I create a code that when pressing a button changes the value of a public int of another script that is used in another scene and make the public int run at the start of that script with the new value assigned? I tried a thousand ways and it doesn’t work out, I don’t know what else to try, on top of that I have little knowledge since I just started programming 2 months ago.
It is the same as changing an int in the same script, except you change the int on a reference to the other script
public OtherScript OtherScriptReference; //Set in inspector
void ButtonPressed()
{
OtherScriptReference.SomePublicVariable++;
}
public SceneLogic sceneLogic;
public void ButtonPressed1()
{
sceneLogic.LevelIndex= 0;
}
public void ButtonPressed2()
{
sceneLogic.LevelIndex = 1;
}
public void ButtonPressed3()
{
sceneLogic.LevelIndex = 2;
}
public void ButtonPressed4()
{
sceneLogic.LevelIndex = 3;
}
I try with that but always excute the first level that is “LevelIndex= 0”. I don’t know why. Maybe if i could put the levelindex at start of the other script should work but i don’t know how, because i can’t put without a number.
The weird thing is that if i put a debug log in ButtonPressed2() and make click in that button it runs the debug log but not change the level index.
Are you sure you’re either not changing LevelIndex somewhere else, or even using the variable at all?
Is the instance of SceneLogic properly marked as a singleton so that you don’t get a brand-new one each time you switch levels?
Some super-simple Singleton examples to take and modify:
Simple Unity3D Singleton (no predefined data):
Unity3D Singleton with Prefab used for predefined data:
These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}
I was able to solve it using playerprefs. Thanks for the help anyway!