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;
{
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
FindObjectOfType<Canvas>();
Example 4: reference to gameobject in different scene unity
public Canvas menu;
void Start()
{
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.sceneUnloaded += OnSceneUnloaded;
}
void OnDestroy()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneUnloaded -= OnSceneUnloaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
menu.gameObject.SetActive(false);
}
void OnSceneUnloaded(Scene current)
{
menu.gameObject.SetActive(true);
}