Created
January 29, 2015 11:51
-
-
Save fversnel/b7af40a04343cb9f4151 to your computer and use it in GitHub Desktop.
Unity Game Object Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
namespace RamjetAnvil.GameObjectFactories | |
{ | |
public struct ObjectFactory { | |
private readonly bool _isObjectActive; | |
private readonly Func<GameObject> _instantiator; | |
public ObjectFactory(bool isObjectActive, Func<GameObject> instantiator) { | |
_isObjectActive = isObjectActive; | |
_instantiator = instantiator; | |
} | |
public bool IsObjectActive { | |
get { return _isObjectActive; } | |
} | |
public Func<GameObject> Instantiator { | |
get { return _instantiator; } | |
} | |
} | |
public static class GameObjectFactory { | |
public static readonly Lazy<GameObject> EmptyInactivePrefab = new Lazy<GameObject>(() => (GameObject)Resources.Load("EmptyInactivePrefab")); | |
public static ObjectFactory FactoryFromPrefab(GameObject prefab) { | |
var isObjectActive = prefab.activeSelf; | |
Func<GameObject> instantiator = () => { | |
// Turn off prefab | |
prefab.SetActive(false); | |
// Instantiate inactive GameObject so that Awake is not yet called | |
var gameObject = (GameObject) GameObject.Instantiate(prefab); | |
// Turn on prefab again | |
prefab.SetActive(isObjectActive); | |
return gameObject; | |
}; | |
return new ObjectFactory(prefab.activeSelf, instantiator); | |
} | |
public static ObjectFactory Adapt(this ObjectFactory factory, Action<GameObject> adapter) { | |
Func<GameObject> newInstantiator = () => { | |
var gameObject = factory.Instantiator(); | |
adapter(gameObject); | |
return gameObject; | |
}; | |
return new ObjectFactory(factory.IsObjectActive, newInstantiator); | |
} | |
public static GameObject InstantiateObject(this ObjectFactory factory) { | |
var gameObject = factory.Instantiator(); | |
// Potentially activate the GameObject so that Awake is finally called | |
gameObject.SetActive(factory.IsObjectActive); | |
return gameObject; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment