Skip to content

Instantly share code, notes, and snippets.

@Stektpotet
Last active July 14, 2016 12:03
Show Gist options
  • Save Stektpotet/1b13005998295d4229861ee5a9bdcdd6 to your computer and use it in GitHub Desktop.
Save Stektpotet/1b13005998295d4229861ee5a9bdcdd6 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 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;
}
}
@Stektpotet
Copy link
Author

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