Monday, June 13, 2016

unity - Unity2D: Don't Destroy On Load UI button Error


I have two UI buttons, an activation button, and a frost button. The activation button activates my frost button when I click on it , using OnClick. I have this script that saves my UI button when a new scene is loaded, however when I click on the activation button to activate my frost button it works a first time, but when I click on the button again (still running the game) I get this error:




MissingReferenceException: The object of type 'FrostScriptButton' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. FrostScriptButton.MyOnLoad (Scene scene, LoadSceneMode sceneMode) (at Assets/Script/FrostScriptButton.cs:34) UnityEngine.SceneManagement.SceneManager.Internal_SceneLoade‌​d (Scene scene, LoadSceneMode mode) (at C:/buildslave/unity/build/artifacts/generated/common/runtime‌​/SceneManagerBinding‌​s.gen.cs:198)



And not showing the button anymore. Anyway this is my script:


void Awake()
{
//We subscribe to the event for loading a scene
SceneManager.sceneLoaded += MyOnLoad;
}

void MyOnLoad(Scene scene,LoadSceneMode sceneMode)

{
//if our button does not have a parent then we will find it a Canvas.
if (gameObject.transform.parent == null)
{
gameObject.transform.SetParent(
GameObject.Find("BackGround Canvas").gameObject.transform, false);
// You might want to use Find with tag here to make sure you will find a canvas
}
}



// Use this for initialization

public void Activate ()
{
frostbutton.SetActive (true);
}

public void LoadLevel()
{

// Before we call the code for loading the level,
//we make sure to set the button as a root object
gameObject.transform.SetParent(null,false);
DontDestroyOnLoad(gameObject);
SceneManager.LoadScene(1);
}

Thank you. :)



Answer



If your game is not UI intense and have couple of Canvases already with hundreds of UI objects in the scene, you can use this solution.



Keep a Canvas that holds all the buttons you don't want to destroy. Make sure it's screen space is overlaid. Give it the highest Sort Order value so it renders over all canvases as well as other overlaid canvases if there are some.


enter image description here


Now add a script which is assigned to the canvas that holding the buttons you don't want to destroy. Put DontDestroyOnLoad(gameObject); at Awake() in this script.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...