unity gameobject across scenes code example

Example 1: dontdestroyonload unity

DontDestroyOnLoad(this.gameObject);

Example 2: dont destroy on load unity

using System.Collections;
using System.Collections.Generic;
using UnityEngine;// Object.DontDestroyOnLoad example.
//
// This script example manages the playing audio. The GameObject with the
// "music" tag is the BackgroundMusic GameObject. The AudioSource has the
// audio attached to the AudioClip.public class DontDestroy : MonoBehaviour
{
    void Awake()
    {
        GameObject[] objs = GameObject.FindGameObjectsWithTag("music");        if (objs.Length > 1)
        {
            Destroy(this.gameObject);
        }        DontDestroyOnLoad(this.gameObject);
    }
}

Example 3: reference to gameobject in different scene unity

//the truth is, you shouldn't. its better to just add delegates to
//SceneManager.sceneLoaded and SceneManager.sceneUnloaded
//if you really need to,
FindObjectOfType<Canvas>();
//searches across all additively loaded scenes

Example 4: reference to gameobject in different scene unity

public Canvas menu;

// Start is called before the first frame update
void Start()
{
    //not in OnEnabled since we want these methods to be called on startup
    SceneManager.sceneLoaded += OnSceneLoaded;
    SceneManager.sceneUnloaded += OnSceneUnloaded;
}

void OnDestroy()
{
    //not in OnDisabled since we want these methods to be removed only when destroyed, not switched out of
    SceneManager.sceneLoaded -= OnSceneLoaded;
    SceneManager.sceneUnloaded -= OnSceneUnloaded;
}

//when a scene is loaded, make this canvas invisible
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
    menu.gameObject.SetActive(false);
}

//when a scene is unloaded, make this canvas visible again
void OnSceneUnloaded(Scene current)
{
    menu.gameObject.SetActive(true);
}