- Home /
Subscribe to an event when the application is loaded
Can I subscribe to an event from scripts who aren't in the initial scene when the game is loaded? Because I have an event called OnLanguageChanged and I need to subscribe to this event from some scripts who aren't called when the game is initialized, such as main menu, options menu, etc.
Is there a way to do this?
Scripts and objects that are not in the currently loaded level do not exist, and are inaccessible.
An exception are objects explicitly made persistent over scene changes, using DontDestroyOnLoad() (but the scene where these are declared have to be loaded at least once, before they become available), and static class members.
Answer by Bunny83 · Jun 22, 2012 at 12:04 AM
If the object with the script / class that contains the event is loaded in a different scene, you have to make sure it isn't destroyed when you change the scene. Usually everything is destroyed when you load a level. In other words you need to use DontDestroyOnLoad on that gameobject. If you load another scene, you can access the gameobject like any other gameobject.
You can:
use a singleton pattern so you can easily access it.
Use FindObjectOfType() to directly get the script if there is only one instance of it.
Answer by Wolfram · Jun 22, 2012 at 12:05 AM
Not sure I understand your question correctly, but if your script providing the event is a persistent script (which it would need to be, using DontDestroyOnLoad()) in your initial scene, and the scripts that need to register to it are not in your initial scene, then just have them register to the event in their OnLevelWasLoaded().
If I misunderstood, please explain the situation more clearly.
Answer by Berenger · Jun 21, 2012 at 09:05 PM
If the object containing this event isn't instantiated, you can't subscribe to that event. You can use a static one though.
Actually the script which contains the Event is called in the first scene, but the subscribers are in other scenes and I don't know how to subscribe them to this event.
As @Berenger says - you would need to use statics in them so that they could be initialized. It would help to know a little about what you are trying to achieve - it's hard to understand how something that isn't loaded needs to know that the app is loaded :)
Your answer
Follow this Question
Related Questions
EventManager with parameters 1 Answer
Issue subscribing to event in managed DLL 0 Answers
Trying to build system without hard coupling 2 Answers
Newbie State Machine Behaviours with Events and Delegates Questions 1 Answer
Fire C# Event 3 Answers