- Home /
How to call a script from an object that is DontDestroyOnLoad
Hello!
I am instantiating the Soomla plugin on my title screen, but I'd like to make a button in another scene call a function from the script that is on an object that only exists in the first scene initially, but it has a DontDestroyOnLoad command.
GameObject exists in the first scene, but doesn't get destroyed and thus is in every scene.
I want a button to call a function from a script that is attached to this GameObject.
How do I call the function?
Answer by zeppike · Jun 04, 2015 at 04:42 PM
How about attaching the script on an empty object in the second scene, than calling it as you would in the first. :) In the long run I would definitely try something like a true singleton pattern. http://unitypatterns.com/singletons/
Firs some scripture for all of us: http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html $$anonymous$$aybe you should tag the GameObject the script is attached on and find it with GameObject.FindGameObjectsWithTag, than call it. Or just use a static reference to the script, like:
public class StoreWindow : $$anonymous$$onoBehaviour
{
public static StoreWindow instance;
void Start ()
{
instance = this;
Application.LoadLevel ("Title Screen");
DontDestroyOnLoad (transform.gameObject);
StoreEvents.OnSoomlaStoreInitialized += onSoomlaStoreInitialized;
SoomlaStore.Initialize (new StoreAssets ());
}
So you can always call StoreWindow.instance.BuyCar2 ();
@zeppike Excellent! Thanks a lot!
Just one problem. I added
public static StoreWindow instance;
void Start () {
instance = this;
}
to the StoreWindow script, but when I call
StoreWindow.instance.BuyCar2();
in another script I get an error:
error CS0103: The name 'StoreWindow' does not exist in the current context.
There is a slight chance that the other script's start is executed before the instance is assigned to the variable. One solution could be to take the instance = this; part to the awake function, or go to Project settings .. Script execution order or something like that, and set your StoreWindow script on the front, before standard time.
Why doesn't the script recognize the StoreWindow class? It recognizes all my other scripts.
Have you tried what I recommended in the previous comment?
Your answer
Follow this Question
Related Questions
List.add() not working when function called by 2nd script 1 Answer
How can I call a method from another script? 3 Answers
Why is calling a function wrong? 2 Answers
Check if a function is no longer being called? 3 Answers
Multiple Cars not working 1 Answer