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.
DontDestroyOnLoad(gameObject);\$\endgroup\$