Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class ComponentExtensions {
- public static T WarnIfNull<T>( this Component lhs, T obj ) where T : Object => (T) lhs.WarnIfNull( obj, typeof( T ) );
- public static Object WarnIfNull( this Component lhs, Object obj, Type type ) {
- #if DEBUG
- if ( obj == null ) GameObjectExtensions.WarnNullComponent( type, lhs.name );
- #endif
- return obj;
- }
- public static T GetOrAddComponent<T>( this Component lhs ) where T : Component => (T) lhs.GetOrAddComponent( typeof( T ) );
- public static Component GetOrAddComponent( this Component lhs, Type type ) {
- return lhs.GetComponent( type ) ?? lhs.gameObject.AddComponent( type );
- }
- public static T GetComponentSafe<T> ( this Component lhs ) where T : Component => (T) lhs.GetComponentSafe( typeof( T ) );
- public static Component GetComponentSafe( this Component lhs, Type type ) {
- return lhs.WarnIfNull( lhs.GetComponent( type ) );
- }
- public static Component LazyGetComponent( this Component lhs, ref Component component, Type type ) {
- //return value ?? lhs.GetComponent( type ); // no good. doesn't update the referenced value
- //return value = (value == null) ? lhs.GetComponent( type ) : value; // not ideal. always reassigns value
- return component ?? (component = lhs.GetComponent( type )); // only assign if null
- }
- public static T LazyGetComponent<T>( this Component lhs, ref T component ) where T : Component {
- return component ?? (component = lhs.GetComponent<T>());
- }
- public static Component LazyGetOrAddComponent( this Component lhs, ref Component component, Type type ) {
- return component ?? (component = lhs.GetOrAddComponent( type ));
- }
- public static T LazyGetOrAddComponent<T>( this Component lhs, ref T component ) where T : Component {
- return component ?? (component = lhs.GetOrAddComponent<T>());
- }
- public static Component LazyGetComponentSafe( this Component lhs, ref Component component, Type type ) {
- return lhs.WarnIfNull( lhs.LazyGetComponent( ref component, type ) );
- }
- public static T LazyGetComponentSafe<T>( this Component lhs, ref T component ) where T : Component {
- return lhs.WarnIfNull( lhs.LazyGetComponent( ref component ) );
- }
- }
Add Comment
Please, Sign In to add comment