Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Interfaces & game design (help appreciated)

Discussion in 'Scripting' started by JanneSilt, Apr 20, 2021.

  1. JanneSilt

    JanneSilt

    Joined:
    Jun 21, 2018
    Posts:
    5
    Hello there,
    I'm creating a multiplayer (MLAPI) Trading Card Game and I'm facing a problem with designing the card specific custom scripts.

    At the moment card specific scripts (attached to every card and responsible of for example checking if card can attack or played as resource) derive from ICard interface which defines all these necessary methods. It seems like interface is useful here, cause every script's name is different (name of the card) and I have to attach the script and access it's methods (I cannot GetComponent<variable>() in runtime but it works when using interfaces) in runtime.

    Well, my current headache comes from it seems like I cannot use virtual methods when inheriting form Interface.

    Cause there are hundreds of cards and tens of methods (that are 90% of the time default) and I would like to define them as virtual in one place and then just override if there is a special case.

    Do I make myself clear? Does anyone have an idea how to solve this problem effective without having to repeat too much code?
     
  2. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    Why not use abstract class
     
  3. JanneSilt

    JanneSilt

    Joined:
    Jun 21, 2018
    Posts:
    5
    Thank you for a prompt answer. Abstract classes solve the inheritance issue but I don't know if I can access a method in abstract class when I have to use a variable as the name of the component? For example how:
    string scriptName;
    c.gameObject.GetComponent<scriptName>().IsSacrifisable();
     
  4. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    No need to save component name
    public abstract class CardBase : MonoBehaviour
    {
    public abstract IsSacrifisable();
    }
    GetComponent<CardBase>().IsSacrifisable();
     
  5. JanneSilt

    JanneSilt

    Joined:
    Jun 21, 2018
    Posts:
    5
    So it works just like with interfaces. Great! Thank you :)