Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Implementing interfaces with arguments only works when the interface is generic

Discussion in 'Scripting' started by cbushofsky, Apr 6, 2021.

  1. cbushofsky

    cbushofsky

    Joined:
    Apr 6, 2021
    Posts:
    3
    Hi everyone, I'm sorry if this has been asked before but I seared for a long time and couldn't find an answer to the problem I'm having. I have an interface
    Code (CSharp):
    1. public interface IAttackManager
    2. {
    3. int Attack(List<Vector2Int> uList);
    4. }
    and implementations of that interface
    Code (CSharp):
    1. public class Unit : MonoBehaviour, IAttackManager
    2. {
    3. public abstract int Attack(List<Vector2Int> uList);
    4. }
    5.  
    6. public class ParticularUnit : Unit
    7. {
    8. public override int Attack(List<Vector2Int> uList)
    9. {
    10. //Do something
    11. }
    but when I compile all this in Unity, it says I didn't implement Attack even though I clearly did. Changing the interface to a generic like this works though for some reason

    Code (CSharp):
    1. public interface IAttackManager<T>
    2. {
    3. int Attack(T uList);
    4. }
    and implementations of that interface
    Code (CSharp):
    1. public class Unit : MonoBehaviour, IAttackManager<List<Vector2Int>>
    2. {
    3. public abstract int Attack(List<Vector2Int> uList);
    4. }
    5.  
    6. public class ParticularUnit : Unit
    7. {
    8. public override int Attack(List<Vector2Int> uList)
    9. {
    10. //Do something
    11. }
    I can't understand why this fixes the problem and why it wouldn't work in the other case. Thanks in advance to anyone who can help!
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,061
    I had to fix some unrelated errors but this compiles fine for me:
    Code (CSharp):
    1. public interface IAttackManager
    2. {
    3.     int Attack(List<Vector2Int> uList);
    4. }
    5.  
    6. public abstract class Unit : MonoBehaviour, IAttackManager
    7. {
    8.     public abstract int Attack(List<Vector2Int> uList);
    9. }
    10.  
    11. public class ParticularUnit : Unit
    12. {
    13.     public override int Attack(List<Vector2Int> uList)
    14.     {
    15.         return 0;
    16.     }
    17. }
    Maybe your interface and implementations are using different
    List<T>
    implementations? Then
    Unit.Attack
    would not qualify as an implementation of the interface.

    If you're using an IDE (Visual Studio, Visual Studio Code, Rider etc), you can let it generate the implementation and then you could compare the generated one to the one you've written yourself.