Skip to content

Instantly share code, notes, and snippets.

@VapidLinus
Last active July 13, 2016 15:24
Show Gist options
  • Save VapidLinus/935fb9ddbcf1cc9689f86e75993494a2 to your computer and use it in GitHub Desktop.
Save VapidLinus/935fb9ddbcf1cc9689f86e75993494a2 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
public abstract class BaseBehaviour : MonoBehaviour
{
public T RequireComponent<T>(Action<T> a) where T : Component
{
T component = gameObject.GetComponent<T>();
if (component == null)
{
component = gameObject.AddComponent<T>();
a(component);
}
return component;
}
}
using UnityEngine;
public class ExampleBehaviour : BaseBehaviour
{
private Rigidbody2D body;
private CircleCollider2D circle;
void Awake()
{
// Multiple lines of code during setup
body = RequireComponent<Rigidbody2D>(b =>
{
b.mass = 10;
b.drag = 1;
b.freezeRotation = true;
});
// Single line of code during setup
circle = RequireComponent<CircleCollider2D>(c => c.radius = 2f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment