Last active
July 14, 2016 12:03
-
-
Save Stektpotet/1b13005998295d4229861ee5a9bdcdd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
/// <summary> | |
/// All scripted behaviour that needs access to internal components should inherit from this. | |
/// </summary> | |
public abstract class ScriptedBehaviour : MonoBehaviour | |
{ | |
/// <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 T RequireComponent<T>() where T : Component | |
{ | |
T component = gameObject.GetComponent<T>(); | |
if(component == null) { component = gameObject.AddComponent<T>(); } | |
return component; | |
} | |
/// <summary> | |
/// Require a component with a specific setup, e.g. change the component properties | |
/// </summary> | |
public T RequireComponent<T>(Action<T> setup) where T : Component | |
{ | |
T component = gameObject.GetComponent<T>(); | |
if(component == null) { component = gameObject.AddComponent<T>(); } | |
setup(component); | |
return component; | |
} | |
/// <summary> | |
/// Requires a component from a gameobject | |
/// Called in Awake() | |
/// </summary> | |
public static T RequireComponentInOther<T>(GameObject other) where T : Component | |
{ | |
T component = other.GetComponent<T>(); | |
if(component == null) { component = other.AddComponent<T>(); } | |
return component; | |
} | |
/// <summary> | |
/// Require a component with a specific setup, e.g. change the component properties | |
/// </summary> | |
public static T RequireComponentInOther<T>(GameObject other, Action<T> setup) where T : Component | |
{ | |
T component = other.GetComponent<T>(); | |
if(component == null) { component = other.AddComponent<T>(); } | |
setup(component); | |
return component; | |
} | |
} |
Can aslo be built in as extension methods: https://gist.github.com/Stektpotet/cc25afca60d89444a7856df07fdf84b2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
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: