Interfaces
Проверено с версией:: 4.1
-
Сложность: Средняя
How to create interfaces and implement them in classes.


Interfaces
Средняя 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
Связанные обучающие материалы
- Classes (Урок)
- Polymorphism (Урок)
- Overriding (Урок)
- Generics (Урок)