Created
June 10, 2016 07:06
-
-
Save kuriharaan/fef4fab61c5c37543c4140d37a95cb51 to your computer and use it in GitHub Desktop.
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 UnityEngine; | |
using System.Collections; | |
using UnityEngine.EventSystems; | |
public static class GameObjectExtension | |
{ | |
public static GameObject InstantiateAsChild(this Transform self, GameObject prefab) | |
{ | |
return self.InstantiateAsChild(prefab, Vector3.zero, Quaternion.identity); | |
} | |
public static GameObject InstantiateAsChild(this Transform self, GameObject prefab, Vector3 position, Quaternion rotation) | |
{ | |
var obj = GameObject.Instantiate(prefab, position, rotation) as GameObject; | |
obj.transform.SetParent(self, false); | |
return obj; | |
} | |
public static void RemoveComponent<T>(this GameObject self) where T : MonoBehaviour | |
{ | |
T component = self.GetComponent<T>(); | |
if( null != component ) | |
{ | |
GameObject.Destroy(component); | |
} | |
} | |
public static T FindComponentToRoot<T>(this GameObject self) where T : UnityEngine.Behaviour | |
{ | |
var component = self.GetComponent<T>(); | |
if( null != component ) | |
{ | |
return component; | |
} | |
var parent = self.transform.parent; | |
if( null == parent ) | |
{ | |
return null; | |
} | |
return parent.gameObject.FindComponentToRoot<T>(); | |
} | |
public static GameObject FindChildRecursively(this GameObject self, string name) | |
{ | |
foreach( Transform t in self.transform ) | |
{ | |
if( name == t.gameObject.name ) | |
{ | |
return t.gameObject; | |
} | |
var next = t.gameObject.FindChildRecursively(name); | |
if( null != next ) | |
{ | |
return next; | |
} | |
} | |
return null; | |
} | |
// call event handler recursively to all parents objects on transform hierarchy. | |
public static void DoParentEventSystemHandler<T>(this Transform self, System.Action<T> action) where T : IEventSystemHandler | |
{ | |
Transform parent = self.transform.parent; | |
while (parent != null) | |
{ | |
foreach (var component in parent.GetComponents<T>()) | |
{ | |
action((T)(IEventSystemHandler)component); | |
} | |
parent = parent.parent; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment