Guest User

Untitled

a guest
Feb 17th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. public static class ComponentExtensions {
  2.  
  3. public static T WarnIfNull<T>( this Component lhs, T obj ) where T : Object => (T) lhs.WarnIfNull( obj, typeof( T ) );
  4. public static Object WarnIfNull( this Component lhs, Object obj, Type type ) {
  5. #if DEBUG
  6. if ( obj == null ) GameObjectExtensions.WarnNullComponent( type, lhs.name );
  7. #endif
  8. return obj;
  9. }
  10.  
  11. public static T GetOrAddComponent<T>( this Component lhs ) where T : Component => (T) lhs.GetOrAddComponent( typeof( T ) );
  12. public static Component GetOrAddComponent( this Component lhs, Type type ) {
  13. return lhs.GetComponent( type ) ?? lhs.gameObject.AddComponent( type );
  14. }
  15.  
  16. public static T GetComponentSafe<T> ( this Component lhs ) where T : Component => (T) lhs.GetComponentSafe( typeof( T ) );
  17. public static Component GetComponentSafe( this Component lhs, Type type ) {
  18. return lhs.WarnIfNull( lhs.GetComponent( type ) );
  19. }
  20.  
  21. public static Component LazyGetComponent( this Component lhs, ref Component component, Type type ) {
  22. //return value ?? lhs.GetComponent( type ); // no good. doesn't update the referenced value
  23. //return value = (value == null) ? lhs.GetComponent( type ) : value; // not ideal. always reassigns value
  24. return component ?? (component = lhs.GetComponent( type )); // only assign if null
  25. }
  26. public static T LazyGetComponent<T>( this Component lhs, ref T component ) where T : Component {
  27. return component ?? (component = lhs.GetComponent<T>());
  28. }
  29.  
  30. public static Component LazyGetOrAddComponent( this Component lhs, ref Component component, Type type ) {
  31. return component ?? (component = lhs.GetOrAddComponent( type ));
  32. }
  33. public static T LazyGetOrAddComponent<T>( this Component lhs, ref T component ) where T : Component {
  34. return component ?? (component = lhs.GetOrAddComponent<T>());
  35. }
  36.  
  37. public static Component LazyGetComponentSafe( this Component lhs, ref Component component, Type type ) {
  38. return lhs.WarnIfNull( lhs.LazyGetComponent( ref component, type ) );
  39. }
  40. public static T LazyGetComponentSafe<T>( this Component lhs, ref T component ) where T : Component {
  41. return lhs.WarnIfNull( lhs.LazyGetComponent( ref component ) );
  42. }
  43.  
  44. }
Add Comment
Please, Sign In to add comment