车TI_Car、和墙TI_Wall这 两 类物体 都继承了一个 接口 TI_Damage,通过另外一个 GameObject的普通组件 Test_Interface,
在 GameObject的组件 Test_Interface 中 使用 TI_Damage 来调用 这两个 物体 的 名字。
本文有2个测试,分别来测试一下 接口的调用 方法。
这一个测试,是分别 在 Car 和 Wall 这两个 物体 分别 设置 了 接口 名字。
---------------------------------------------------------------------------------------------------------------------------------------------
接口逻辑图:
代码逻辑图:
步骤:
新建3个物体,命名
建立一个接口类
using System.Collections;//可以注释掉 using System.Collections.Generic;//可以注释掉 using UnityEngine;//可以注释掉 public interface TI_Damage{ string Name { get; set; } int health { get; set; } }
给物体Wall 建立一个类 TI_wall : MonoBehaviour,TI_Damage
如何实现 继承MonoBehaviour的同时又 继承 接口类 TI_Damage,参考资料1,本文不赘述
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TI_wall : MonoBehaviour,TI_Damage { public int health {get;set; } public string Name {get;set;} // Use this for initialization void Start () { Name = "wall"; Debug.Log(" WALL " + Name); } }
给物体Car 建立一个类 TI_car : MonoBehaviour,TI_Damage
如何实现 继承MonoBehaviour的同时又 继承 接口类 TI_Damage,参考资料1,本文不赘述
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TI_car : MonoBehaviour,TI_Damage { public int health {get;set;} public string Name {get;set;} // Use this for initialization void Start () { Name = "car"; Debug.Log(" CAR "+Name); } }using System.Collections; using System.Collections.Generic; using UnityEngine; public class test_interface : MonoBehaviour { private TI_car ticar; private TI_wall tiwall; public GameObject GO_ticar; public GameObject GO_tiwall; private int index; // Use this for initialization void Start () { ticar = new TI_car(); tiwall = new TI_wall(); ticar.Name = "this is car"; tiwall.Name = "this is wall"; Debug.Log(ticar.Name+tiwall.Name); index = 0; } private void Update() { if (Input.GetKeyDown(KeyCode.X)) { index++; string str_car = GO_ticar.GetComponent<TI_Damage>().Name; string str_wall = GO_tiwall.GetComponent<TI_Damage>().Name; Debug.Log(str_car + " "+index+" " + str_wall); } } }
显示结果
---------------------------------------------------------------------------------------------------------------------------------------------
不分别 在 Car 和 Wall 这两个物体 的组件中 分别 赋予名字。
而是在管理 这两个物体 的GameObject 中Test_Interface 中 ,赋予 这两个物体 Car 和 Wall 名字, 再通过
接口TI_Damage 来找到这两个物体 Car 物体 的TI_Car 和 Wall 物体 的TI_Wall,并显示他们的名字。
结果:
---------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------------
参考资料:
1.[Unity&接口]子类即继承接口类也继承MonoBehaviour的快速操作和重构实现
http://blog.csdn.net/bulademian/article/details/72884513
2.
3.
4.
5.