Unity3D Singleton Design Pattern

 회사에서 Unity3D 기반 RPG 했다가 게임브리오 기반 MMORPG 했다가 바쁘네요 ㅎ; 이번에 정리할 것은 이슈는 아니지만 워낙에 C# 초보에다가 유니티3D 초보다 보니, 제 자신이 나중에 찾아보기위해 이렇게 정리를 해봅니다.

 현재 유니티3D AssetBundle(에셋번들) 처리를 위한 Patch Tool까지는 어느정도 마무리 된 상태입니다. cocos2d-x 용으로 만들었던 패치툴이 C#이었기 때문에 각 AssetBundle마다의 버전 관리 기능만 추가해서 후딱 끝냈습니다.

 이제 유니티3D 게임에서 패치 프로세스를 처리해야하는데 Manager다 보니 당연히 싱글톤 패턴이 필요하게 되었습니다. 구글링 해보니 역시 유니티3D는 자료가 참 많아요~ 아래는 패치 메니져는 아니고 기존에 널리고 널린 에셋번들 메니져 컴포넌트 가지고 싱클턴화 해봤습니다.


using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

/// 
/// Asset bundle manager.
/// 
public class AssetBundleManager : MonoBehaviour {
 
 /// 
 /// The _instance.
 /// 
 private static AssetBundleManager _instance = null;
 
 /// 
 /// Gets the instance.
 /// 
 /// 
 /// The instance.
 /// 
 public static AssetBundleManager Instance {
  get {
   if (_instance == null) {
    /// 기존에 만든 놈이 있다면 가져온다.
    _instance = FindObjectOfType(typeof(AssetBundleManager)) as AssetBundleManager;
    if (_instance == null) {
     /// 없다면 빈 GameObject를 만들어 AssetBundleManager 컴포넌트를 추가한다.
     _instance = new GameObject("AssetBundleManager").AddComponent();
    }
   }
   return _instance;
  }
 }
 
 static private Dictionary dicAssetBundleRef;
 
 static AssetBundleManager() {
  dicAssetBundleRef = new Dictionary();
 }
 
 private class AssetBundleRef {
  public AssetBundle assetBundle = null;
  public int iVersion;
  public string strUrl;
  public AssetBundleRef(string strUrl, int iVersion) {
   this.strUrl = strUrl;
   this.iVersion = iVersion;
  }
 };
 
 public static AssetBundle getAssetBundle(string strUrl, int iVersion) {
  string strKey = strUrl + iVersion.ToString();
  AssetBundleRef abRef;
  
  if (dicAssetBundleRef.TryGetValue(strKey, out abRef)) {
   return abRef.assetBundle;
  } else {
   return null;
  }
 }
 
 public static void Unload(string strUrl, int iVersion, bool bAllObj) {
  string strKey = strUrl + iVersion.ToString();
  AssetBundleRef abRef;
  
  if (dicAssetBundleRef.TryGetValue(strKey, out abRef)) {
   abRef.assetBundle.Unload(bAllObj);
   abRef.assetBundle = null;
   dicAssetBundleRef.Remove(strKey);
  }
 }
 
 /// 
 /// Awake this instance.
 /// 
 void Awake () {
  /// 신을 변경해도 Singleton 객체를 날리지 못하게 한다.
  DontDestroyOnLoad(this);
 }

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
 
 /// 
 /// Raises the application quit event.
 /// 
 void OnApplicationQuit () {
  /// 어플리케이션 종료시 Singleton 객체를 날려준다.
  _instance = null;
 }
}
 유니티3D는 싱글톤 컴포넌트든 뭐든간에 꼭 GameObject에 붙여서 사용을 해야하는군요. 아, 객체의 메소드가 static으로 되어있다면 오브젝트에 안 붙여서 다른데서 호출은 가능하더군요.

 쓰레드 세이프 하지도 않은 간단 싱글톤 패턴을 정리해봤습니다. 더 나아가서 Generic하게 템플릿 싱글톤 패턴을 쓰려면 링크를 확인하면 되겠네요.

댓글

이 블로그의 인기 게시물

'xxx.exe' 프로그램을 시작할 수 없습니다. 지정된 파일을 찾을 수 없습니다.

goorm IDE에서 node.js 프로젝트로 Hello World Simple Server 만들어 띄워보기

애드센스 수익을 웨스턴 유니온으로 수표대신 현금으로 지급 받아보자.