Skip to content

Instantly share code, notes, and snippets.

@hsandt
Created May 19, 2016 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsandt/b6fda88700c5974f8490cb54713de553 to your computer and use it in GitHub Desktop.
Save hsandt/b6fda88700c5974f8490cb54713de553 to your computer and use it in GitHub Desktop.
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 = Vector3.zero;
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);
clone.name = name;
return clone;
}
}
@hsandt
Copy link
Author

hsandt 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