Snippets

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

Created by Alex Darby last modified
//------------------------------------------------------------------------
// 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 AlexRoseIsLazyAndCantBeBotheredToType
{
	//------------------------------------------------------------------------	
	// 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();
	}
}

Comments (0)

HTTPS SSH

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