1. 程式人生 > >Unity單例模式-基類

Unity單例模式-基類

using System;
using UnityEngine;

/// <summary>
/// 單例基類
/// </summary>
public abstract class SingleBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    /// <summary>
    /// 單例
    /// </summary>
    public static T Singleton { get; private set; }

    /// <summary>
    /// 賦值
    /// </summary>
    public virtual void Awake()
    {
        //單例必須唯一,重複就拋錯
        if (Singleton != null)
            throw new Exception("Repeated Singleton");

        Singleton = this as T;
    }
}