"this"是指游戏对象或类还是 c# 脚本的名称?



我试图了解如何实现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,他将游戏对象拖入其中。该代码的目标是允许音频在场景中有增无减地播放,即不会在新场景加载时破坏包含音频源的游戏对象。

我很困惑"this"是指gameObject还是MusicController类。当我读到this.InstantiateController();时,似乎"这个"一定是MusicController公共类。但是,在下面

if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if(this != Instance) {
Destroy(this.gameObject);
}

似乎"this"必须是指链接到名为 Instance 的音乐控制器公共静态变量的游戏对象。

所以我很困惑。是哪个?还是完全是别的什么?

我尝试阅读 6 年前的这篇以前的堆栈溢出帖子,但不幸的是仍然感到困惑。 Unity3D 脚本(c# 脚本、JavaScript(中的 'this' 关键字

提前感谢您的帮助。

您发布的代码正在制作音乐组件的简单单例。

this始终引用类的实例。因此,在这种情况下,它是MusicController的实例。

this.gameObject只是意味着您正在获得附加到MusicControllergameObject

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 pointer (this) isn't the same as the pointer set to the 
//Instance static property
Destroy(this.gameObject);
}

我希望这能澄清其中的一些问题。

这就像在说我自己。

在组件的 Unity 脚本中,它指的是您所在的类实例。

相关内容

最新更新