- Home /
Carry UI to new scene without moving the canvas
I have a group of UI elements that I want to persist between scenes. The UI elements are of the only canvas in the scene, so each time before there is a scene change, I unparent the UI elements and make them DontDestryOnLoad. After the scene changes, I reparent them to the present canvas.
My script for the UIs:
public void BeforeChangeScenes()
{
transform.SetParent(null);
DontDestroyOnLoad(gameObject);
}
void OnLevelWasLoaded(int level)
{
Canvas[] canvases = GameObject.FindObjectsOfType<Canvas>();
transform.SetParent(canvases[0].transform);
RectTransform rectTransform = gameObject.GetComponent<RectTransform>();
rectTransform.anchorMax = new Vector2(1f, 0f);
rectTransform.anchorMin = new Vector2(0f, 1f);
}
BeforeChanceScenes is called before another script calls SceneManager.LoadScene
The unparenting, loading new scene, reparenting all succeeded. My problem is that after it reparents itself to the canvas it does not show up in the game or the scene. I can only see it in the inspector.
Yes, they are visible in hierarchy but not game view.
Answer by otomo · Jul 09, 2016 at 09:17 PM
I just tested this with a simple setup. It seems that UI Components get destroyed on Scene Load when they are not attached to a canvas. Even if you set them as DontDestroyOnLoad. I am not sure if that is a bug or intended behavior. A workaround would be to move the whole canvas to the new scene, move the UI Components to the new Canvas and destroy the old one, if you really need a new canvas in the new scene.
I don't think they get destroyed if they are set DontDestroyOnLoad, since I still see it in the hierarchy, but I will try the new canvas idea.
Answer by ahmadian · Dec 21, 2017 at 08:43 AM
You can have multiple canvases in a scene. Create a canvas only for those elements and make that canvas persistent using DontDestroyOnLoad. This way there is no need to destroy the old canvas or to rearrange the elements.