我试图了解如何为Unity3D实现DontDestroyOnLoad,并且遇到了这篇文章:https://honkbarkstudios.com/developer-blog/dontdestroyonload-tutorial/
[本文由Christian Engvall撰写,提供了以下代码作为教程:
using UnityEngine;
using System.Collections;
public class MusicController : MonoBehaviour {
public static MusicController Instance;
void Awake()
{
this.InstantiateController();
}
private void InstantiateController() {
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if(this != Instance) {
Destroy(this.gameObject);
}
}
}
其他信息:Engvall创建了一个名为MusicController的游戏对象,并为其附加了音频源。他还附加了一个C#脚本,也称为MusicController。然后,脚本包含类型为MusicController的公共静态变量,他将gameObject拖入其中。该代码的目标是允许音频在各个场景之间畅通无阻地播放,即在加载新场景时不要破坏包含音频源的gameObject。
我对'this'是指gameObject还是MusicController类感到困惑。当我阅读this.InstantiateController();
时,似乎'this'必须是MusicController公共类。但是,在这里下面
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if(this != Instance) {
Destroy(this.gameObject);
}
似乎'this'必须引用链接到名为Instance的MusicController公共静态变量的gameObject。
所以我很困惑。哪有还是完全其他?
我曾尝试阅读6年前的上一篇堆栈溢出文章,但很遗憾,我仍然感到困惑。The 'this' keyword in Unity3D scripts (c# script, JavaScript)
谢谢您的帮助。
在组件的统一脚本中,它引用您所在的类实例。
this
始终引用类的实例。因此,在这种情况下,它是MusicController
的实例。
[this.gameObject
仅表示您正在获得附加到gameObject
的MusicController
。
Instance
是静态的,这意味着将只有一个“实例”固定在内存中的某个位置。 MusicComponent
的每个实例都可以访问该单个“实例”对象。因此,在您突出显示的方法中:
//I'm an instance of MusicComponent and I want to see if
//some other instance exists. If there's another music component already
//then Instance will NOT be null
if(Instance == null)
{
//Now I know I'm the only MusicComponent created so I'll set this static property to me
//This lets any new MusicComponents created know that there is already one alive
//and they should not stay alive
Instance = this;
DontDestroyOnLoad(this);
}
else if(this != Instance) {
//Turns out, I'm not the first instance of MusicComponent created because
//because another one has already set themselves to static property
//I know this but my point (this) isn't the same as the pointer set to the
//Instance static property
Destroy(this.gameObject);
}