问题描述
MissingComponentException: 没有附加到渲染器"robot2"游戏对象,但脚本正在尝试访问它.你可能需要为游戏对象robot2"添加一个渲染器.或者你的脚本需要在使用之前检查组件是否已附加.UnityEngine.Renderer.get_material()(在<94c5f4c38cdc42d2b006f8badef04394>:0) ColorChange.Start()(在资产/ColorChange.cs:21)
我的 Unity 程序中有一个 fbx robots2,它已作为资产导入.我想在程序启动时更改颜色,但收到此消息.如何在 Unity 中渲染我的 fbx?
I have a fbx robot2 in my Unity program, it have been imported as a Asset. I want change the color when program start, but I get this message. How could I render my fbx in Unity?
public Color colorStart = Color.red;
public Color colorEnd = Color.green;
public Renderer rend;
// Start is called before the first frame update
void Start()
{
rend = GetComponent<Renderer>();
rend.material.color = colorStart;
}
推荐答案
基本上错误信息说明了一切:
Basically the error message says it all:
GetComponent
仅返回附加的组件与您的脚本相同 GameObject
.
但是您的 robo2
没有网格,因此也没有 Renderer
.
But your robo2
has no mesh and therefore also no Renderer
.
在您的情况下,您更愿意使用 GetComponentsInChildren
而是返回附加到 GameObject
本身的所有相应组件,您的脚本附加到它或递归嵌套在它下面的任何子对象
What you rather want to do in your case would be using GetComponentsInChildren
which rather returns all according components attached to the GameObject
itself your script is attached to or any child object nested under it recursively
void Start()
{
// pass true in order to also include disabled or inactive child Renderer
foreach(var rend in GetComponentsInChildren<Renderer>(true))
{
rend.material.color = colorStart;
}
}
这篇关于“robot2"没有附加“渲染器".游戏对象,但脚本试图访问它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!