车TI_Car、和墙TI_Wall这两类物体都继承了一个接口TI_Damage,通过另外一个GameObject的普通组件Test_Interface,
在GameObject的组件Test_Interface中使用TI_Damage来调用这两个物体的名字。
本文有2个测试,分别来测试一下接口的调用方法。
测试1
通过接口调用继承接口类Interface的普通类
这一个测试,是分别在Car和Wall这两个物体分别设置了接口名字。
---------------------------------------------------------------------------------------------------------------------------------------------
接口逻辑:
代码逻辑:
步骤:
新建3个物体,命名
建立一个接口类
using System.Collections;//可以注释掉
using System.Collections.Generic;//可以注释掉
using UnityEngine;//可以注释掉
public interface TI_Damage{
string Name { get; set; }
int health { get; set; }
}
如何实现继承MonoBehaviour的同时又继承接口类TI_Damage,参考资料本文不赘述
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,参考资料本文不赘述
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().Name;
string str_wall = GO_tiwall.GetComponent().Name;
Debug.Log(str_car + ' '+index+' ' + str_wall);
}
}
}
显示结果
---------------------------------------------------------------------------------------------------------------------------------------------
测试2
不分别在Car和Wall这两个物体的组件中分别赋予名字。
而是在管理这两个物体的GameObject中Test_Interface中,赋予这两个物体Car和Wall名字,再通过
接口TI_Damage来找到这两个物体Car物体的TI_Car和Wall物体的TI_Wall,并显示他们的名字。
结果:
---------------------------------------------------------------------------------------------------------------------------------------------
测试3
分别在TI_wall和TI_car中添加变量num,结果显示,只有接口类TI_Damage中包含的变量。
才能通过查找该物体的接口类TI_Damage组件找到这些接口类TI_Damage中的变量。
---------------------------------------------------------------------------------------------------------------------------------------------
文章为作者独立观点,不代表股票交易接口观点