Unity3D 接口使用


C#怎么實現多繼承?

說起多繼承,首先大家可以想想這個問題:你知道在C#中怎么實現多繼承嗎?

主流的答案無非2種。

答案一:用接口啊,一個類可以繼承自多個接口的。
答案二:C#不支持多繼承,C++才支持多繼承,多繼承會讓代碼變得很亂,因此微軟在設計C#的時候放棄了多繼承。

先說說什么是真正意義的多繼承。真正的多繼承應該是像C++那樣的,而不是說像在C#里面一個類繼承了多個接口就叫多繼承。在C#中,如果一個類實現了多個接口,那么要為每個接口寫實現,如果接口被多個類繼承,那么就會有重復的代碼,這顯然是無法接受的。

然而C++那樣的多繼承也確確實實給編碼帶來了很大的麻煩,我也相信微軟真的是因為意識到了多繼承的不合理之處才在C#中擯棄了這個特性。其他的在這里就不多說了,請看案例

案例:

假如我們要寫一個背包系統,背包里自然有很多物品,那我們該怎么識別 我們當前使用的是什么物品呢?

筆者在這里使用接口來簡單實現一個背包

 

IA.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace abc
{
    public interface IA
    {
        void ItemFunction();
    }

}

 

HpScript.cs

using UnityEngine;
using abc;
public class HpScript : MonoBehaviour, IA
{
    public void ItemFunction()
    {
        ItmeDrugFunction();
    }

    void ItmeDrugFunction()
    {
        Debug.Log("Hp");
    }
}

Mpscript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class Mpscript : MonoBehaviour, IA
{
    void IA.ItemFunction()
    {
        ItmeDrugFunction();
    }
    void ItmeDrugFunction()
    {
        Debug.Log("Mp");
    }
}

SwordScript.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class SwordScript : MonoBehaviour, IA
{
    void IA.ItemFunction()
    {
        ItmeDrugFunction();
    }
    void ItmeDrugFunction()
    {
        Debug.Log("Swrod");
    }
}

Backpack.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using abc;
public class Backpack : MonoBehaviour {

    public GameObject itme;
    internal Transform itmeChilld;
    void Start () {
      
        if(itme != null && itme.transform.GetChild(2) != null) //如果當前節點不為空並且它子節點第二個元素也不為空
        {
            itmeChilld = itme.transform.GetChild(2);
            itmeChilld.GetComponent<IA>().ItemFunction();    //使用接口訪問
            Debug.Log("Name : " + itmeChilld.name);
        }
    }
}

我們可以測試訪問以下,看看是不是我們想要的結果

經過測試 是我們想要的結果,就這樣一個簡單的背包就做好了。喜歡的請點個贊哦!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM