繁体   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