Created
August 26, 2019 21:23
-
-
Save rob5300/3d24309c94317bef6179bc355bbbfbaa to your computer and use it in GitHub Desktop.
Example of using Interfaces with MonoBehaviours in Unity
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 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