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

C#, interfaces, this. and the unit testing blog article

Discussion in 'Scripting' started by IDoAllTheWork, Nov 5, 2015.

  1. IDoAllTheWork

    IDoAllTheWork

    Joined:
    Jun 20, 2015
    Posts:
    19
    Hey folks,

    after completing my first test game I've been working through lots of tutorials, blog articles and so on to get better. While looking for information about unit testing in Unity3D, I stumbled upon an unity blog article. I already watched the tutorial on interfaces, but somehow the example code looks confusing to me:




    1. controller.SetMovementController(this);
    From what I understand, this function call passes the object (SpaceshipMotor instance) to the function. But the function expects an IMovementController object. How can this work? Or is the compiler intelligent enough to see the types don't match, and instead passes on the IMovementController interface of the SpaceshipMotor?

    2. Implementation of the interfaces
    The SpaceshipMotor implements the two interfaces. Why does the SpaceshipController need the private fields for the interfaces? Is it done this way to make the function calls of the interface functions independent from an instance of SpaceshipMotor (which is not in there)?

    Thanks in advance for any help!
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
  3. IDoAllTheWork

    IDoAllTheWork

    Joined:
    Jun 20, 2015
    Posts:
    19
    Thanks, but the images are taken directly from said unity blog article.
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    1. Inheritance and polymorphism. It wants an IMovementController and it works because SpaceshipMotor is a IMovementController. If SpaceshipMotor didn't implement that interface then it would fail to compile.

    2. Yes - the code seems weird from a functional perspective but the article in question is geared towards unit testing of MonoBehaviours. Going back to the first question - it doesn't care about the specific information; it just needs to know the contractual nature of the object being passed in, which the interface provides. In plain speak - "I don't care what you are as long as you have a MoveHorizontaly and MoveVerticaly method in you somewhere."
     
    IDoAllTheWork likes this.
  5. IDoAllTheWork

    IDoAllTheWork

    Joined:
    Jun 20, 2015
    Posts:
    19
    Thanks, that helped a lot!