Friday, December 11, 2015

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


I have a UI button as a child under my background canvas. What I want to do is to save the button through out scene, I tried using DontDestroy OnLoad but It saved ay canvas and everything under my canvas, rather than saving just the button. Anyway this is my DontDestroyOnLoad script:


void Awake()
{
DontDestroyOnLoad(transform.root.gameObject);
}

Thank you. :)



Answer



Well I wiped up a script that does this but the solution seem janky. Use it at your own risk.



using UnityEngine;
using UnityEngine.SceneManagement;

public class TestButtonPersist : MonoBehaviour
{
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("Canvas").gameObject.transform, false);
// You might want to use Find with tag here to make sure you will find a canvas
}

}

// This is where the magic happens
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);

}
}

The thing is you need to call transform.SetParent(null,false) for the object before the scene changes so you will have to do this from your code that loads a new scene.


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...