|
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 类。
|