Simple and common way of writing Unity singleton

The advantage of script singleton is that it is convenient for other scripts to call the content exposed by the singleton script.

But it should be noted that when using a singleton, you must first ensure that there is only one object mounted by the singleton script in the game.

For example, if there is only one game manager in the game, then it can be single-instanced, and the simplest steps are 2 steps:

/// <summary>
/// 游戏管理器
/// </summary>
public class GameManager : MonoBehaviour
{
    //定义一个当前类的公开,静态,当前类类型返回值的一个字段;
    public static GameManager Instance;

    //在 Awake 事件方法中完成该字段的赋值;
    private void Awake()
    {
        Instance = this;
    }
}

This this refers to the current script GameManager, Instance is this type of field, any name is fine, I personally prefer to write it like this, pay attention to the assignment in Awake, otherwise you will encounter a null reference bug later.

Other scripts call singletoned script methods:

GameManager.Instance.方法/属性/字段

Because the own script has been assigned to Instance in Awake, it is only necessary to use the methods and fields exposed by the GameManager script in the form of script name.Instance.method name.

Guess you like

Origin blog.csdn.net/weixin_55532142/article/details/124389066