Search Unity

Global Prefabs

Discussion in 'Scripting' started by xewlupus, Apr 6, 2011.

  1. xewlupus

    xewlupus

    Joined:
    Apr 3, 2009
    Posts:
    2
    Dreamed up a nifty way to do global prefabs; thought I would share:

    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. // Original Author: max.kaufmann@gmail.com
    5. // In the Editor, Global.Inst will lazily initialize the prefab at any time
    6. // In a build, "bootstrap" it by placing the prefab in your title scene
    7.  
    8. public class Global : MonoBehaviour {
    9.    
    10.     static Global sInst;
    11.    
    12.     public static Global Inst {
    13.         get {
    14.             #if UNITY_EDITOR
    15.                 if (!sInst) {
    16.                     Instantiate(UnityEditor.AssetDatabase.LoadAssetFromPath("Assets/Path/To.Prefab"));
    17.                 }
    18.             #endif
    19.             return sInst;
    20.         }
    21.     }
    22.    
    23.     void Awake() {
    24.         sInst = this;
    25.         DontDestroyOnLoad(this);
    26.     }
    27.  
    28. }
    29.