Skip to content

Instantly share code, notes, and snippets.

@rob5300
Created August 26, 2019 21:23
Show Gist options
  • Save rob5300/3d24309c94317bef6179bc355bbbfbaa to your computer and use it in GitHub Desktop.
Save rob5300/3d24309c94317bef6179bc355bbbfbaa to your computer and use it in GitHub Desktop.
Example of using Interfaces with MonoBehaviours in Unity
using UnityEngine;
public class MyBox : MonoBehaviour, IInteractable{
//We must implement this due to the interface
public void Interact(){
Debug.Log("I was interacted with!");
Destroy(gameObject);
}
}
public interface IInteractable {
void Interact();
}
//Have me in a new file
public class PlayerInteract : MonoBehaviour {
void Update(){
//Get your gameobject somehow as ob
IInteractable interactable = ob.GetComponent<IInteractable>() ?? ob.GetComponentInParent<IInteractable>();
if(interactable != null){
//You know you have an interactable object, something that had a mono that also implemented the interface
//Be warned as if the object has more than one component implementing the interface you may need to get components and execute on them all.
interactable.Interact();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment