Search code examples
c#unity-game-enginefacebook-unity-sdk

Where to put Fb.init() when changing levels?


I have two different levels and in my second level I want to use facebook to submit a highscore. So I've added the facebook sdk functions (from the fb doc) to my 2nd level unity c# script. First time loading this level works fine but after I'm done and returning to the first level and loading the second level again it complains because fb.init is already loaded.

My awake() looks like this:

if (!FB.IsLoggedIn)   {
   FB.Init(SetInit, OnHideUnity);
}

Where do I need to put the FB.Init function so its not getting called again? Both levels are getting loaded again.


Solution

  • As user3811917 has stated, FB init should only be called once. There are many times in Unity development that you only want a function to be called once during the lifecycle of the application, and the most common way of addressing this is to create a separate loading or bootstrapping scene.

    Basically, what this scene does is load, then immediately (on start perhaps) transition to the first scene of your game. By adding scripts to this scene (that run on awake), you can call several functions that will only be called once throughout the life of you application. This is useful for setting up third party plugins which need to be initialised only once. You can also place non-destroyable singleton objects in this scene, so that you can create and initialise scene persistent objects, that are only created once.