统一中的单例模式删除重复对象
gamemanager.cs
private void Awake()
{
//check if instance is null, if null then create
if (instance == null) {
//refers to the GameManager class
instance = this;
//dont destroy gamemanger game object when loading new scene
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
}
为什么使用单身模式需要销毁(gameObject)?为什么首先要创建第二个实例?
GameManager.cs
private void Awake()
{
//check if instance is null, if null then create
if (instance == null) {
//refers to the GameManager class
instance = this;
//dont destroy gamemanger game object when loading new scene
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject);
}
}
Why is Destroy(gameObject) necessary with a singleton pattern? Why would a second instance be created in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以通过不同的原因创建。例如:
gameBoct.Addcompont&lt ; myaweSometype>()
),因此您无法确定对象不会重复,因此您必须确保只有第一个创建的实例才能活着
It can be created by different reasons. For example:
gameObject.AddComponent<MyAwesomeType>()
)So as you cannot be sure that object will not be duplicated, you have to be sure that only the first created instance stays alive