Skip to content

Instantly share code, notes, and snippets.

@NickMercer
Last active October 20, 2021 19:10
Show Gist options
  • Save NickMercer/b42f6fd0adde9642f0b458da04ea4fcb to your computer and use it in GitHub Desktop.
Save NickMercer/b42f6fd0adde9642f0b458da04ea4fcb to your computer and use it in GitHub Desktop.
Pattern for reusable Unity Components using interfaces.
public class DemoAirHorn : MonoBehaviour, IThingBehaviour
{
public void DoAThing()
{
Debug.Log("EEEEEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
}
public int ReturnAThing(int number)
{
return number + 1;
}
}
public class DemoPlayer : MonoBehaviour, IThingBehaviour
{
public void DoAThing()
{
Debug.Log("I, a player, have done a thing.");
}
public int ReturnAThing(int number)
{
return 10 * number;
}
}
public interface IThingBehaviour
{
void DoAThing();
int ReturnAThing(int number);
}
using UnityEngine;
public class ThingComponent : MonoBehaviour
{
private IThingBehaviour _thingBehaviour = null;
//On awake, the component finds a component on the object with the required interface.
private void Awake()
{
_thingBehaviour = GetComponent<IThingBehaviour>();
if(_thingBehaviour == null)
{
Debug.Log($"{gameObject.name} is missing a MonoBehaviour that implements IThingBehaviour!");
}
}
//Example of internal component logic that triggers method on the interface implementation component.
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
_thingBehaviour.DoAThing();
}
if(Input.GetKeyDown(KeyCode.Enter))
{
var number = _thingBehaviour.ReturnAThing(12);
Debug.Log(number);
}
}
}
@NickMercer
Copy link
Author

A way in Unity to make components you can add to a GameObject and only need to couple the GameObject's main script to them. The components don't need to know anything about the object they're attached to, only that they have a component that implements the interface. To add the component to a new object, you just add it in the inspector and implement the interface on a component on your GameObject.

@NickMercer
Copy link
Author

The workflow for this would be:

  1. Add ThingComponent to the GameObject.
  2. Add the IThingBehaviour interface to a new or existing script on your object.
  3. Implement the interface with your object specific implementation.

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