상상 너머 그 무언가...

Unity C# Interface 사용법 본문

개발관련(Development)/유니티3D(Unity3D)

Unity C# Interface 사용법

Clack 2012. 2. 16. 16:54


점점 복잡해지고 다양해지는 클래스들을 만들게 되다보니 인터페이스의 필요성을 느끼게 되었다.

유니티에서는 인터페이스를 어떻게 사용할까?

인터페이스 선언
public interface ICat{

void EatFish( string FishName );
}

인터페이스를 적용하는 클래스1
using UnityEngine;
using System.Collections;

public class MyCatTest : MonoBehaviour, ICat {

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void EatFish( string FishName )
{
Debug.Log(" myCat eat a fish " + FishName);
}

인터페이스를 적용하는 클래스2
using UnityEngine;
using System.Collections;

public class BadCatTest : MonoBehaviour, ICat {

// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void EatFish( string FishName )
{
Debug.Log(" badCat eat a fish " + FishName);
}
}


인터페이스 변수에 클래스 대입 후 함수 호출하기
using UnityEngine;
using System.Collections;

public class InterfaceTest : MonoBehaviour {
private ICat cat;
void Awake()
{
cat = GameObject.Find("Cat").GetComponent<MyCatTest>();
}
// Use this for initialization
void Start () {
cat.EatFish( " bananaFish " );
}
// Update is called once per frame
void Update () {
}
}