Using Interface and Implementing it!
I needed a simple way to show UI pop up in my project and to edit the texts fields, so when the object is triggered it will show a different text depending on the object where it is. Sounds cool right!? :)
For example you can use it in situations like if you click a book it says “You found a book!” And when you click a bed “Do you want to rest?”.
So how did I do this… ? With Interface! :) I had never heard of it untill a friend of mine taught me how it works and how to use it. And for real, this was a real lifesaver for me! :D
Enough of me rambling about this, let’s start coding…. :)
- So what we need first is the Interface script. There you will write a method and a property that you will call from other classes.
- To declare an interface, it’s good that the name starts with capital I and is followed with a capital letter so then it’s IInteractable.
- Then you need to create a string property which will be shown in those UI.
- And in the end you need a method.
Here you can see the whole Interface script that we need for this. Doesn’t look like much right?
So then we need a Class that implements our Interface script right? Let’s make that happen! :)
Let’s start with Implementing the script!
To implement the IInteractable script we made.
You do it by adding a comma after an inheritance like Monobehaviour.
As you can see above after I wrote IInteractable, I used Visual Studios own option to automatically Implement the script and to add the code we needed. It’s so useful and time-saving! :)
Changing the code
After implementing the interface you got a few lines of code which you have to edit for your own use.
But firstly you need to create a string variable where you will add your text.
After that you can use [SerializeField] to edit the text in the Inspector.
Like shown below.
To get the ineractText you use
public string GetInteractText => interactText;
What will your Interact() do?
Now when that is done what we need is to decide what the
public void Interact() will do.
In my case I needed the Interact to Destroy my tree with Delay after I click it and press the “yes” button.
After making the interactText, we can edit the text field in Inspectory to say whatever you want! :)
That is all we need for now to get the Interface working.
In other article I will show how I triggered the Interact() after clicking an UI Button in Tree GameObject and using OnClick() event.
Thank you for reading this and I hope you learned something new like I did! :)