1. 程式人生 > >unity泛型單例

unity泛型單例

我們要使用Unity3d在Object類中提供了一個靜態函式 :Object.DontDestroyOnLoad (Object target) . 載入新場景的時候使單例物件不被自動銷燬

作為 MonoBehaviour 因為我們可能需要協同程式,所以使用 Lock同步

用法示例

MyClass.cs

public class MyClass : MonoBehaviour {
	void Awake () {
		Debug.Log(Manager.Instance.myGlobalVar);
	}
}

Manager.cs

public class Manager : Singleton<
Manager> { protected Manager () {} // guarantee this will be always a singleton only - can't use the constructor!   public string myGlobalVar = "whatever"; }

執行

Singleton.cs

using UnityEngine;
 
/// <summary>
/// Be aware this will not prevent a non singleton constructor
///   such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class. /// /// As a note, this is made as MonoBehaviour because we need Coroutines. /// </summary> public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { private static T _instance;   private static object _lock = new object
();   public static T Instance { get { if (applicationIsQuitting) { Debug.LogWarning("[Singleton] Instance '"+ typeof(T) + "' already destroyed on application quit." + " Won't create again - returning null."); return null; }   lock(_lock) { if (_instance == null) { _instance = (T) FindObjectOfType(typeof(T));   if ( FindObjectsOfType(typeof(T)).Length > 1 ) { Debug.LogError("[Singleton] Something went really wrong " + " - there should never be more than 1 singleton!" + " Reopening the scene might fix it."); return _instance; }   if (_instance == null) { GameObject singleton = new GameObject(); _instance = singleton.AddComponent<T>(); singleton.name = "(singleton) "+ typeof(T).ToString();   DontDestroyOnLoad(singleton);   Debug.Log("[Singleton] An instance of " + typeof(T) + " is needed in the scene, so '" + singleton + "' was created with DontDestroyOnLoad."); } else { Debug.Log("[Singleton] Using instance already created: " + _instance.gameObject.name); } }   return _instance; } } }   private static bool applicationIsQuitting = false; /// <summary> /// When Unity quits, it destroys objects in a random order. /// In principle, a Singleton is only destroyed when application quits. /// If any script calls Instance after it have been destroyed, /// it will create a buggy ghost object that will stay on the Editor scene /// even after stopping playing the Application. Really bad! /// So, this was made to be sure we're not creating that buggy ghost object. /// </summary> public void OnDestroy () { applicationIsQuitting = true; } }

要求

新增新庫之前它將檢查元件是否存在。所以使用泛型,進行抽象

(從GetOrAddComponent MonoBehaviourExtended.cs)

static public class MethodExtensionForMonoBehaviourTransform {
	/// <summary>
	/// Gets or add a component. Usage example:
	/// BoxCollider boxCollider = transform.GetOrAddComponent<BoxCollider>();
	/// </summary>
	static public T GetOrAddComponent<T> (this Component child) where T: Component {
		T result = child.GetComponent<T>();
		if (result == null) {
			result = child.gameObject.AddComponent<T>();
		}
		return result;
	}
}





相關推薦

unity

我們要使用Unity3d在Object類中提供了一個靜態函式 :Object.DontDestroyOnLoad (Object target) . 載入新場景的時候使單例物件不被自動銷燬作為 Mono

Unity中的指令碼工具

在Unity遊戲開發中,寫指令碼經常會用到單例模式,所以就寫了一個公用的泛型單例類方便使用,也為了以後開發偷點懶 public class Singleton<T> where T :

C# 簡單的

//SharedInstance.cs using System; using System.Collections.Generic; using System.Linq; using System.

Python設計模式 - 創建 - 模式(Singleton) - 十種

mod 再次 bsp 裝飾 __str__ 環境 使用場合 導入 加載 對於很多開發人員來說,單例模式算是比較簡單常用、也是最早接觸的設計模式了,仔細研究起來單例模式似乎又不想看起來那麽簡單。我們知道單例模式適用於提供全局唯一訪問點,頻繁需要創建及銷毀對象等場合,的確方

設計模式(4)—— 建立 ——(Singleton)

導航 首先通過懶漢式的單例模式簡單程式碼實現作為開頭,發現有執行緒安全問題,並且在此懶漢模式程式碼上進行改進,衍生出同步懶漢設計模式,雙重檢查懶漢設計模式。另外還有靜態內部類方式實現單例,它是一種基於類初始化的延遲載入解決方案。 與懶漢式相對應的是餓漢式單例模式,其在類載入時就進

設計模式——建立——模式

一、單例模式定義: 單例模式確保某個類只有一個例項,而且自行例項化並向整個系統提供這個例項。在計算機系統中,執行緒池、快取、日誌物件、對話方塊、印表機、顯示卡的驅動程式物件常被設計成單例。這些應用都或多或少具有資源管理器的功能。每臺計算機可以有若干個印表機,但只能有一個Printer Spool

Unity--函式呼叫

using UnityEngine; public abstract class Animal {     public abstract void Walk(int step); } public class Dog : Animal {     public over

Unity中的模式基類

在unity中有兩種單例型別,一種是普通單例,即普通c#類,另一種是繼承了MonoBehaviour的單例。 普通單例: public abstract class CSharpSingletion<T> where T : new() {

設計模式-建立-模式

單例模式:對於類的單例模式設計,就是採取一定的方法保證在整個軟體系統中,對某個類只能存在一個物件例項,並且該類只提供一個取得其物件例項的方法(靜態方法)。 單例模式有8種方式:   1、餓漢式(靜態常量)   // 2、餓漢式(靜態程式碼塊)   3、懶漢式(執行緒不安全)   4、懶漢式(執行緒安

Unity之物件池(物件池和物件池)

眾所周知,遊戲開發中記憶體和效能一直是影響使用者遊戲體驗的至關重要的兩個因素,這次說一說物件池的概念。 物件池意義是將遊戲中反覆建立銷燬的物件進行多次利用,從而避免大量物件的銷燬與建立而造成CPU的負

使用實現模式提供者

MSDN 上有解釋泛型是什麼: C#泛型簡介 。今天我就用泛型重構我的程式碼。以前每個類的單例模式是這麼寫的: 以前的單例模式程式碼 public class myClass {     publ

模式(類)

 在專案開發過程中,經常會涉及到多個採用單例模式的類,對每個類都要進行單例的處理,甚是不爽。 下面使用泛型類解決了這個問題,只要簡單繼承就可以了,程式碼如下: namespace LogHelper { using System; /// <sum

C#模式的定義

取自某熱門網遊 using System; public class Singleton<T> where T : class, new() { private static T _Instance; public static T Instance

通過寫一個通用的

寫一個通用的單例,並且進行資料初始化以及單例的釋放 public class TSingleton<T> where T : new() { static T m_instanc

android singleton 模式的

<pre name="code" class="java">public abstract class Singleton<T> { private T mInstance; protected abstract T create();

創建設計模式(模式)

創建型設計模式 true 自己 singleton span 創建 final 調用 ati 單例模式有以下特點:  1、單例類只能有一個實例。  2、單例類必須自己創建自己的唯一實例。  3、單例類必須給所有其他對象提供這一實例。 一、懶漢式單例 //懶漢式單例類.在第

創建模式 模式

pri com 創建型模式 私有 變量 模式 靜態 分享 靜態方法 創建型模式 單例模式 /** * 創建型模式 單例模式 懶漢式 * GoF對單例模式的定義是:保證一個類、只有一個實例存在,同時提供能對該實例加以訪問的全局訪問方法。 * * 實現單例步驟常用

C#中Predicate與Func委托的用法實

public pan html 加水印 pre wid bcf 委托 ora 本文以實例形式分析了C#中Predicate<T>與Func<T, bool>泛型委托的用法,分享給大家供大家參考之用。具體如下: 先來看看下面的例子:static vo

C#Dictionary的用法實詳解

contains code medium 計算 aaa alt -i 硬件 ole 本文以實例形式講述了C#中的泛型Dictionary的用法。具有很好的實用價值。分享給大家供大家參考。具體如下: 泛型最常見的用途是泛型集合,命名空間System.Collections.

C#設計模式之一模式(Singleton Pattern)【創建

nal 設計 類庫 開發 避免 sum behavior 並且 負責 原文:C#設計模式之一單例模式(Singleton Pattern)【創建型】一、引言 看了李建忠老師的講的設計模式已經有一段時間了(這段時間大概有一年多了),自己還沒有寫過自己的、有關設計模