Skip to content

Instantly share code, notes, and snippets.

@Stektpotet
Last active July 14, 2016 12:04
Show Gist options
  • Save Stektpotet/cc25afca60d89444a7856df07fdf84b2 to your computer and use it in GitHub Desktop.
Save Stektpotet/cc25afca60d89444a7856df07fdf84b2 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
/// <summary>
/// All scripted behaviour that needs access to internal components should inherit from this.
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Requires a component from the gameobject currently beeing scripted
/// without the need for constant use of GetComponent or messy inspectors
/// using multiple [SerializeField]-attributes.
///
/// Called in Awake()
/// </summary>
public static T RequireComponent<T>(this MonoBehaviour behaviour) where T : Component
{
T component = behaviour.GetComponent<T>();
if(component == null) { component = behaviour.gameObject.AddComponent<T>(); }
return component;
}
/// <summary>
/// Require a component with a specific setup, e.g. change the component properties
/// </summary>
public static T RequireComponent<T>(this MonoBehaviour behaviour, Action<T> setup) where T : Component
{
T component = behaviour.GetComponent<T>();
if(component == null) { component = behaviour.gameObject.AddComponent<T>(); }
setup(component);
return component;
}
}
@Stektpotet
Copy link
Author

Stektpotet commented Jul 14, 2016

Usage:

private Rigidbody2D rigid;
private DistanceJoint2D distJoint;

void Awake()
{
    rigid = this.RequireComponent<Rigidbody2D>();
    distJoint = this.RequireComponent(joint => joint.enabled = false));
}

Taking use of the an action as parameter you can simply change properties of the aqquired component, either using lambda expressions or functions. This can be of great use if you need minor changes in the component properties. It can also be used like this:

private Rigidbody2D rigid;
private DistanceJoint2D distJoint;

void Awake()
{
    rigid = this.RequireComponent<Rigidbody2D>();
    distJoint = this.RequireComponent<DistanceJoint2D>(SetupDistanceJoint);
}
stativ void SetupDistanceJoint(DistanceJoint2D distJoint)
{
    distJoint.enabled = false;
    distJoint.enableCollision=true;
    distJoint.distance = 5.0f;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment