I've been using this small script as a component to any object I want to not be destroyed at scene loading.
public class DontDestroy : MonoBehaviour
{
void Start()
{
DontDestroyOnLoad(gameObject);
}
}
It has been working fine. It works for my GameOver canvas which I've been using for a long time whilst making the game.
Today I added the same script to a new AndroidControls Canvas I made. In the Editor it worked fine. Then I built it for Android to run on my physical phone (Galaxy S10). It gave me a Null exception.
It turned out to be caused by the AndroidControls Canvas being destroyed between scene loading (even though as I say, I tested in Editor for a few runs and it didnt get destroyed). And it gets a little weirder because after the attempted build to APK, and fail on physical device, it then failed to work in the editor. It continues to not work in each test after this in Editor, however if I remove the component and add it again, the entire process then repeats.
Please help as I don't have a clue how to start fixing this. The only thing I can imagine it being wrong is it started as soon as I used this script on two canvas's simultaneously. (I highly doubt I am correct but it's the only thing I could notice at all that might be causing this).
This picture actually shows my DontDestroy component is attached to Canvas_AndroidControls, but in the Hierarchy you can already see that it is not in the DontDestroyOnLoad section (excuse the pink overlay for play-mode):
Maybe relevant, here are some of my specs:
Win 10
Unity 2020.3.5f1 (Just downloaded NDK/SDK for Android today via Unity Modules)
Android 11 (Samsung Galaxy S10)