Unity 通过接口调用方法

***********************************************定义接口***************************************************************

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IWalk
{
    void Walking();

}

***********************************************************************************************************************

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IFly
{
    void Fly(IWalk walk);

}

******************************************************实现*************************************************************

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Walk : MonoBehaviour,IWalk {

    public void Walking()
    {
        Debug.Log("Walking");
    }

}

************************************************************************************************************************

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestFly : MonoBehaviour,IFly{

    private GameObject go;
    IWalk walk;
// Use this for initialization
void Start () {
        //获取场景中的对象
        go = GameObject.Find("Cube");
      
        if(go  !=null){
            walk = go.GetComponent <Walk>() as IWalk;
            if(walk !=null ){
                Debug.Log("Walk 不为空,赋值成功");
            }
        }
}
   
// Update is called once per frame
void Update () {
if(Input .GetKeyDown(KeyCode.Q)){
            Fly(walk);
        }
}

    public void Fly(IWalk walk)
    {
        Debug.Log(walk);
        walk.Walking();
    }
}

posted @ 2018-06-12 14:21  低小调  阅读(826)  评论(0编辑  收藏  举报