Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Unity engine GameObject extensions : get component, instantiate and clone objects
public static class GameObjectExtensions {
/// Try to get component of type T, log error if none found
public static T GetComponentOrFail<T>(this GameObject gameObject) where T : Component {
T component = gameObject.GetComponent<T>();
if (component == null)
throw ExceptionsUtil.CreateExceptionFormat("No component of type {0} found on {1}.", typeof(T), gameObject);
return component;
/// Instantiate prefab / clone game object (helper to avoid casting to GameObject every time)
public static GameObject Instantiate (this GameObject model) {
if (model == null) throw ExceptionsUtil.CreateExceptionFormat("Cannot instantiate null model.");
GameObject gameObjectInstance = Object.Instantiate(model) as GameObject;
return gameObjectInstance;
/// Instantiate prefab / clone game object at parent's position
public static GameObject InstantiateUnder (this GameObject model, Transform parentTr, bool keepLocalPosition = false) {
GameObject gameObjectInstance = Instantiate(model);
gameObjectInstance.transform.SetParent(parentTr, false);
if (!keepLocalPosition)
gameObjectInstance.transform.localPosition =;
return gameObjectInstance;
/// Duplicate object under the same parent with the same local position, with a new name. This breaks any prefab link.
public static GameObject Duplicate (this GameObject model, string name) {
GameObject clone = InstantiateUnder(model, model.transform.parent, true); = name;
return clone;

This comment has been minimized.

Copy link
Owner Author

commented May 20, 2016

ExceptionsUtil.CreateExceptionFormat creates a new Exception from a format string + object parameters using string.Format().
I will post a gist for that later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.