簡體   English   中英

如何在C#中訪問子類的方法?

[英]How to access a method of a child class in c#?

當它返回某個類的實例時,我需要訪問gameObject.AddComponent() essential參數...

gameObject.AddComponent()函數的返回類型為Component

項目中的繼承看起來是這樣的:

Object <- Component <- Behaviour <- MonoBehaviour <- TDefault <- ...

其中A < B表示“ BA繼承”。

我無權訪問MonoBehaviour或其父母。 它們由引擎提供。

TDefault是我從中繼承除TEssential所有類的類。 它是我寫的。 它具有TEssential類型的essential屬性

轉換print(gameObject.AddComponent(effect_name) as TDefault); 打印null

print((gameObject.AddComponent(effect_name) as dynamic));

產生

內部編譯器錯誤。 有關更多信息,請參見控制台日志。 輸出為:錯誤CS0518:未定義或導入預定義類型System.Runtime.CompilerServices.CallSite錯誤CS0518:未定義或導入預定義類型System.Runtime.CompilerServices.CallSite 1'

我嘗試添加

using System.Runtime.CompilerServices.CallSite;

但這只會改變錯誤

內部編譯器錯誤。 有關更多信息,請參見控制台日志。 輸出為:錯誤CS0518: System.Runtime.CompilerServices.CallSite' is not defined or imported error CS0518: The predefined type System.Runtime.CompilerServices.CallSite System.Runtime.CompilerServices.CallSite' is not defined or imported error CS0518: The predefined type System.Runtime.CompilerServices.CallSite`1

我確定返回的變量的類型為... 內置編輯器可以正確顯示它。

我如何獲得財產?

添加組件具有通用重載,因此您應該可以執行以下操作:

effect_name newComponent = gameObject.AddComponent<effect_name>();

經過更多的研究。 您確定effect_name繼承了TDefault嗎?

如果要訪問連接到游戲對象(無論是不是孩子)的類(或組件)的方法,可以使用gameObject.GetComponent<Myclass(or component)>().MyMethod([params])

如果要訪問游戲object -> gameobject.Transform.getChild(#)

如果要添加組件,請使用AddComponent方法。

解決方案是強制轉換為接口:

1)

    using UnityEngine;
    using System.Collections;
    using NExtensionMethods;

    public class TDefault:MonoBehaviour,IDefault
    {
        public  TEssentail essential=new TEssentail();
        public TEssentail get_essential()
        {
            if(essential==null)
                essential=new TEssentail();
            return essential;
        }

        public TDefault ()
        {
        }
    }

2)

using UnityEngine;
using System.Collections;

public interface IDefault
{

    TEssentail get_essential();
}

3) TEssentail ess=(gameObject.AddComponent(effect_name) as IDefault).get_essential();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM