Below you can find a series of Method Extensions for types in Unity that add simplistic yet useful functionality. This list will be updated periodically to add new useful method extensions.
Camera Extensions
A set of Extension Methods for usage with the UnityEngine.Camera class
RaycastFromScreenPoint
This Method Extension simplifies the mouse ray casting code often needed for selection interaction
public static bool RaycastFromScreenPoint(this Camera self, Vector2 screenPoint, out RaycastHit hitInfo) { return Physics.Raycast(self.ScreenPointToRay(screenPoint), out hitInfo); }
RaycastFromScreenPoint (Variant)
A variant similar to the previous one, but simply returning a UnityEngine.GameObject if a hit has occured. This method also utilizes the previously described method.
public static GameObject RaycastFromScreenPoint(this Camera self, Vector2 screenPoint) { RaycastHit hitInfo; if(RaycastFromScreenPoint(self, screenPoint, out hitInfo)) { return hitInfo.transform.gameObject; } return null; }
Transform Extensions
A set of Method Extensions for usage with the UnityEngine.Transform class
GetRoot
Returns the root (Transform without a parent) of a Transform. This method is useful if you want to figure out what the top level Transform in a given hierarchy is.
public static Transform GetRoot(this Transform self) { Transform transform = self; while(transform.parent != null) { transform = transform.parent; } return transform; }
GetAbsolutePath
Returns the absolute path of a Transform within the hierarchy. The method also allows you to specify a custom delimiter.
public static string GetAbsolutePath(this Transform self, string delimiter = "/") { string path = self.name; Transform transform = self; while(transform.parent != null) { transform = transform.parent; path = path.Insert(0, transform.name + delimiter); } return path; }
GetRandomChild
Returns a random child from a given Transform. Please note that this method only returns the immediate childs of a Transform. Also, the method uses the UnityEngine.Random class. We suggest you modify this method if you require your randomness to be more deterministic.
public static Transform GetRandomChild(this Transform self) { return self.GetChild(Random.Range(0, self.childCount)); }
GameObject Extensions
A set of Method Extensions for usage with the UnityEngine.GameObject class
Clone
Returns a clone of the GameObject using the UnityEngine.Object.Instantiate method.
public static GameObject Clone(this GameObject self) { return Object.Instantiate(self); }
DestroyChildren
Destroys all children associated with the GameObject
public static void DestroyChildren(this GameObject self) { foreach(Transform transform in self.transform) { Object.Destroy(transform.gameObject); } }