Scripting
Intermediate

Interfaces

Checked with version: 4.1

-

Difficulty: Intermediate

-

Date: 13 Mar 2014

How to create interfaces and implement them in classes.

Interfaces

Intermediate Scripting

Interfaces

Code snippet

using UnityEngine;
using System.Collections;

//This is a basic interface with a single required
//method.
public interface IKillable
{
    void Kill();
}

//This is a generic interface where T is a placeholder
//for a data type that will be provided by the 
//implementing class.
public interface IDamageable<T>
{
    void Damage(T damageTaken);
}
#pragma strict

//This is a basic interface with a single required
//method.
public interface IKillable
{
    function Kill();
}

//Javascript does not allow generic types to
//be defined, so this version of IDamageable
//uses a float type
public interface IDamageable
{
    function Damage(damageTaken : float);
}
import UnityEngine
import System.Collections


//This is a basic interface with a single required
//method.
public interface IKillable:

    def Kill()


//This is a generic interface where T is a placeholder
//for a data type that will be provided by the 
//implementing class.
public interface IDamageable[of T]:

    def Damage(damageTaken as T)

Avatar Class

Code snippet

using UnityEngine;
using System.Collections;

public class Avatar : MonoBehaviour, IKillable, IDamageable<float>
{
    //The required method of the IKillable interface
    public void Kill()
    {
        //Do something fun
    }
    
    //The required method of the IDamageable interface
    public void Damage(float damageTaken)
    {
        //Do something fun
    }
}
#pragma strict

public class Avatar extends MonoBehaviour implements IKillable, IDamageable
{
    //The required method of the IKillable interface
    public function Kill()
    {
        //Do something fun
    }
    
    //The required method of the IDamageable interface
    public function Damage(damageTaken : float)
    {
        //Do something fun
    }
}
import UnityEngine
import System.Collections


public class Avatar(MonoBehaviour, IKillable, IDamageable[of single]):

    //The required method of the IKillable interface
    public def Kill():
        pass
        //Do something fun

    
    //The required method of the IDamageable interface
    public def Damage(damageTaken as single):
        pass
        //Do something fun
Overriding
Extension Methods

Related tutorials

Got it

The Unity Software License Agreement and Privacy Policy have been updated.

We use cookies to ensure that we give you the best experience on our website. Click here for more information.