I have a BattleState scene wich is loaded when I press a button on the previous scene.
When this button is pressed I want a particlular intance to be eaqual to another one, but I’m getting a Null Refence Exeption error.
In the BattleState scene I have two main scripts witch are both singletons.
In the first, I’ve several instances of “enemies”
enemy1 = new BaseEnemy(100, 0, 5, 3);
enemy2 = new BaseEnemy(100, 0, 10, 5);
...
In the other one, that hadles the battle logic, I have this instance
public BaseEnemy enemy;
and when the button is pressed, in the scene wich is loading the BattleState scene, I want this to happen :
public void loadscene()
{
SceneManager.LoadScene("BattleScene");
BattleState.instance.enemy = EnemyDefine.instance.enemy1;
}
The sccene loads fine, but the line after seems to have no effect (Refence Exeption error.) when I try to acces variables of the enemy instance in BattleState scene.
What am I missing ?
Can’t I mess around with scripts whose scene is loaded afterwards ?
Is the previous scene “unloaded” when I open another one ?
To resolve, you could turn your loadscene() into a coroutine, yielding null after the call to SceneManager.LoadScene, and before you try to do anything else. This will ensure that you’re on the next frame before you try to access stuff in the loaded scene. This technique can also be extended to work with SceneManager.LoadSceneAsync quite easily if you encounter issues with frame stutter.
Thanks for your answer.
I just played around with your suggestion but still can’t get it to work, same type of error.
Is there a way to know (through the messaging system maybe) wich action was taken that brought me into the actual scene (i.e the button that was pressed to load the scene) ?
Tried this without the Coroutine and it wouldn’t work, so the Coroutine is key here, even though I don’t fully get why since we do not destroy the scene right after the call.
Maybe this could’ve been done with the yield only, but who knows, it works.