返回首页DA系统C#IDE文件同步服务屏保 今天是: 2026-05-05    "立夏"  夏季的第一个节气,表示盛夏时节的正式开始

搜索
热搜: linux 技术
Hi~登录注册
查看: 1517|回复: 0

[转载] 【转载】ArgumentException: GetComponent requires that the requested component ‘XX‘ derives from...

[复制链接]
发表于 2025-2-18 10:02:38 | 显示全部楼层 |阅读模式
ArgumentException: GetComponent requires that the requested component ‘XX‘ derives from...

转载作者:野奔在山外的猫


开发平台:Unity 2020
编程平台:Visual Studio 2020
使用语言:CSharp


一、问题描述




备注:这是一个开发者对 Unity 认知存在错误所产生的方法。

问题代码信息:

var thisMat = transform.GetComponent<Materials>();


或者

var thisMat = this.GetComponent<GameObject>();

二、问题原因
2.1 理解:成为 Component 的条件




在 Unity 中成为 Component 的条件是继承于 MonoBehaviour 类对象。该继承模式下的脚本将允许以组件视窗模式呈现。即 Inspector 属性面板上的挂载。原则上,只要是能够在游戏对象上添加的对象均有继承 MonoBehaviour。

2.2 理解:Component 与 Material 关系




GetComponent<T>() 通常作为索引组件具体对象。此处涉及其爷爷对象 Component 类。该 Component 类是 MonoBehaviour 的爷爷类。但同时也是 Material 的旁系子类(即 object 父类)。

最终解释:在拥有同系父类的情况下,出现 GetComponent<Material>() 却 “未提示该行代码异常” 的原因也就清晰明了。因为 Material 并未直接或间接继承 Component 类。


三、解决方案:使用继承 Component 对象进行索引属性。


public void Example()
{
        var thisMaterial = transform.GetComponent<MeshRenderer>().Materials[0];
}


或者

public void Example()
{
        GameObject GameObj =this.transform.gameObject;
}


为方便管理这类特别的继承关系对象。例如 Material 能够在 MeshRenderer 组件中被找到。可以使用 GetComponents<MeshRenderer>().Materials 获取对象。如果细致能发现 MeshRenderer 继承于 Renderer 类。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册成为修仙之旅的少年~

x
游客
回复
*滑块验证:

DA论坛飞机票来了~
快速回复 返回顶部 返回列表