unity3d之切换场景不销毁物体

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 /// <summary>
 5 /// 背景音乐脚本
 6 /// </summary>
 7 public class AudioBackground : MonoBehaviour {
 8 
 9     static AudioBackground StaticObject;
10 
11     private bool LastMusicOn = true;
12 
13     void Start()
14     {
15 
16     }
17     public static AudioBackground instance
18     {
19         get
20         {
21             if (StaticObject == null)
22             {
23                 StaticObject = FindObjectOfType<AudioBackground>();
24                 DontDestroyOnLoad(StaticObject.gameObject);
25             }
26             return StaticObject;
27         }
28     }
29     void Awake()
30     {
31         if (StaticObject == null)
32         {
33             StaticObject = this;
34             DontDestroyOnLoad(this);
35         }
36         else if (this != StaticObject)
37         {
38             Destroy(gameObject);
39         }
40 
41     }
42     void Update()
43     {
44         if (MainController.musicOn != LastMusicOn)
45         {
46             LastMusicOn = MainController.musicOn;
47             OnMusicChanged();
48         }
49     }
50     private void OnMusicChanged()
51     {
52         if (MainController.musicOn)
53         {
54             gameObject.GetComponent<AudioSource>().Play();
55         }
56         else
57         {
58             gameObject.GetComponent<AudioSource>().Pause();
59         }
60     }
61 }
原文地址:https://www.cnblogs.com/ninomiya/p/6834762.html