Snippets

Alex Darby Alex Rose Doesn't Like to Type More Than Necessary

Updated by Alex Darby

File snippet.txt Modified

  • Ignore whitespace
  • Hide word diff
 // n.b. this creates an unattached valid instance of the type and returns it if one isn't present
 // this instance is not attached to a game object, will do nothing, and has an associated GC cost
 //------------------------------------------------------------------------
-public static class AlexRoseIsLazyAndCantBeBotheredToTypeUnitPatcher
+public static class AlexRoseIsLazyAndCantBeBotheredToType
 {
 	//------------------------------------------------------------------------	
 	// usage exactly as GetComponent< T >() but must be called via this in 
Created by Alex Darby

File snippet.txt Added

  • Ignore whitespace
  • Hide word diff
+//------------------------------------------------------------------------
+// now you too can write code which assumes components are there without worrying about it!
+//
+// usage requires a reference to an instance of a MonoBehaviour derived type
+// 
+// n.b. this creates an unattached valid instance of the type and returns it if one isn't present
+// this instance is not attached to a game object, will do nothing, and has an associated GC cost
+//------------------------------------------------------------------------
+public static class AlexRoseIsLazyAndCantBeBotheredToTypeUnitPatcher
+{
+	//------------------------------------------------------------------------	
+	// usage exactly as GetComponent< T >() but must be called via this in 
+	// member functions:
+	// 
+	// this.GetComponentSafe< SomeComponentClass >().member = assignFrom;
+	//------------------------------------------------------------------------	
+	public static TypeToFind GetComponentSafe< TypeToFind >( this MonoBehaviour cSelf ) where TypeToFind : Component, new()
+	{
+		TypeToFind cInstanceOrNull = cSelf.GetComponent< TypeToFind >();
+		if( null != cInstanceOrNull )
+		{
+			return cInstanceOrNull;
+		}
+		return new TypeToFind();
+	}
+
+	//------------------------------------------------------------------------	
+	// usage exactly as GetComponentInParent< T >() but must be called via this in 
+	// member functions:
+	// 
+	// this.GetComponentInParent< SomeComponentClass >().member = assignFrom;
+	//------------------------------------------------------------------------	
+	public static TypeToFind GetComponentInParentSafe< TypeToFind >( this MonoBehaviour cSelf ) where TypeToFind : Component, new()
+	{
+		TypeToFind cInstanceOrNull = cSelf.GetComponentInParent< TypeToFind >();
+		if( null != cInstanceOrNull )
+		{
+			return cInstanceOrNull;
+		}
+		return new TypeToFind();
+	}
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.