- Home /
Generalized call of specific methods
I have a script for dragging around cards, and right now each card has its own method - named DoTheThing() - which does that card's individual thing. At present these scripts each have their own if statement:
public void Update()
{
if (Input.GetKeyDown(KeyCode.Return) && isHolding.cardObject == this.gameObject)
{
DoTheThing();
gc.TurnCleanup();
}
}
And this is...fine? I guess? I mean, it works. But it seems this could be refactored onto a single script on the play area that calls the DoTheThing method from (current card sitting there) if there were a reliable way to (a) get a reference to the individual script and (b) convince the computer that the reference holds the DoTheThing method.
System.Type.GetType(GetComponentInChildren<Card>().name).DoTheThing();
This is the line of code I attempted, and I think it fulfills condition (a) but fails at (b). I'm pretty sure it is actually targeting the correct thing - The first child object it'll find will be the card, which bears the same name as its attached script because that's how I attach the scripts at runtime. But it won't compile, because it can't be assured that the type I'm grabbing is actually a script with a DoTheThing method attached. Does anyone have a clever way of getting a whole system of card scripts - all of which do their own things - to activate from a central, generalized "when this is on the play zone, press enter" command, without each card checking for that every frame?
Answer by Llama_w_2Ls · May 07, 2021 at 07:13 PM
Use interfaces. They allow you to enforce a script to implement certain methods or properties, and so the compiler is certain that they exist. For example:
public interface ICard
{
void DoTheThing();
}
Now, any class that inherits from 'ICard', must implement the method 'DoTheThing', which you can see here:
public class MyCard : MonoBehaviour, ICard
{
// This method must exist, or else compiler will throw errors
public void DoTheThing()
{
Debug.Log("I did the thing");
}
}
The great thing about multi-inheritance, is that now, any class inheriting from ICard, can have its 'DoTheThing' method called, without having to know the type of the class. For example: instead of GetComponent<Card>().DoTheThing
, you can just write: GetComponent<ICard>().DoTheThing
. It works with every type, inheriting from ICard, as above.
I followed this advice and cross-referenced with a couple tutorial videos to make sure I was doing it right, but...Yeah, it really is as easy as you make it look. What an excellent tool to add to one's program$$anonymous$$g options!
Your answer
Follow this Question
Related Questions
How to create a custom "On..." method? 2 Answers
Queue methods. 0 Answers
Calling a variable based on a variables name? 1 Answer
Variable Not Changing In Method 1 Answer
Trouble calling a function... 1 Answer