【问题标题】:There is no 'Renderer' attached to the "robot2" game object, but a script is trying to access it“robot2”游戏对象没有附加“渲染器”,但脚本正在尝试访问它
【发布时间】:2020-02-18 19:40:07
【问题描述】:

MissingComponentException:没有“渲染器”附加到 “robot2”游戏对象,但脚本正在尝试访问它。你 可能需要为游戏对象“robot2”添加一个渲染器。或者你的 脚本需要在使用之前检查组件是否已附加。 unityEngine.Renderer.get_material() (在 :0) ColorChange.Start () (在 资产/ColorChange.cs:21)

我的 Unity 程序中有一个 fbx robots2,它已作为资产导入。我想在程序启动时更改颜色,但我收到此消息。如何在 Unity 中渲染我的 fbx?

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;
}

【问题讨论】:

  • Robot2 没有附加渲染器组件。看起来有可能有渲染器的子游戏对象。 GetComponent() 中不包含子游戏对象;查找。
  • 如何渲染和改变孩子的颜色?

标签: unity3d


【解决方案1】:

基本上错误信息说明了一切:

GetComponent 仅返回附加到 相同 GameObject 的组件作为您的脚本。

但是您的robo2 没有网格,因此也没有Renderer


在您的情况下,您更愿意使用GetComponentsInChildren,它会返回附加到您的脚本所附加到的GameObject 本身的所有相应组件或递归嵌套在其下的任何子对象

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;
    }
}

【讨论】:

  • 什么是汽车?
  • @Liliymas 是一个错字^^ 我在智能手机上写了这个,很抱歉;)我注意到另一个我的自动更正删除了s .. 它应该是GetComponentsInChildren 以便不仅获得第一个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多