Last active
October 20, 2021 19:10
-
-
Save NickMercer/b42f6fd0adde9642f0b458da04ea4fcb to your computer and use it in GitHub Desktop.
Pattern for reusable Unity Components using interfaces.
This file contains hidden or 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
public class DemoAirHorn : MonoBehaviour, IThingBehaviour | |
{ | |
public void DoAThing() | |
{ | |
Debug.Log("EEEEEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"); | |
} | |
public int ReturnAThing(int number) | |
{ | |
return number + 1; | |
} | |
} |
This file contains hidden or 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
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; | |
} | |
} |
This file contains hidden or 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
public interface IThingBehaviour | |
{ | |
void DoAThing(); | |
int ReturnAThing(int number); | |
} |
This file contains hidden or 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; | |
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The workflow for this would be: