One way is to use a shared object such as a GameManager to facilitate communications between scenes. When entities come up they can register themselves with the GameManager so other things can find them.
Alternately you can look for things via tag, or else via component, in this case some component that uniquely marks the GameObject where the animator is.
public static GameManager3D Instance;
public Animator doorAnim;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
MissingReferenceException: The object of type ‘Animator’ has been destroyed but you are still trying to access it.
private Animator anim;
private void Start()
{
instance = GameObject.Find("GameManager").GetComponent<GameManager>();
anim = GameManager3D.Instance.doorAnim.GetComponent<Animator>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player2D"))
{
if (instance.coinCount > 1)
{
// all coins are collected
// house door will be opened.
Debug.Log(anim);
// play door animation
anim.SetBool("isOpen", true);
collectedAllCoinsPanel.SetActive(true);
}
any idea why animator is destroyed? and how to fix it?
when i change the scene , actually this singleton cannot keep the gameobject with it rather only the singleton gameobject is persistence between the scene change.
how to fix it? how to keep also the referenced gameobject in the singleton class?
Any GameObject you want kept from one scene to the next has to either be marked DontDestroyOnLoad, or parented to something that is. Nothing special about that with Singletons. That’s just Unity.
This is unlikely to be code. It’s more likely to be how you set stuff up. If you change scenes, all other things being equal, you need to get new references to the new things in the new scene.
If you keep things from the previous scene (with DontDestroyOnLoad), then you need to NOT have them in the next scene, otherwise you’ll have double cameras, double audio listeners, etc.