如何在脚本中将渲染器添加到游戏对象?

How can i add a renderer to gameobject in script?

GameObject cube = Cube.CreatePrimitive(Cube.CubePivotPoint.UPLEFT);
cube.GetComponent<Renderer>().material.color = Color.blue;

当我分配颜色时,在线上出现异常:

cube.GetComponent<Renderer>().material.color = Color.blue;

MissingComponentException: There is no 'Renderer' attached to the "CubeHolder" game object, but a script is trying to access it. You probably need to add a Renderer to the game object "CubeHolder". Or your script needs to check if the component is attached before using it.

注意:

我正在使用 答案中的 CUBE class 创建立方体,而不是 Unity 的 GameObject.CreatePrimitive 函数。

当我写 时,我忘了提到立方体的渲染器现在是另一个对象的子对象。

您不需要将 RendererMeshRenderer 添加到多维数据集。它已经在那里了。立方体只是一个子对象,父对象名为 CubeHolder。您需要使用 GetComponentInChildren 来获取它的 Renderer.

cube.GetComponent<Renderer>().material.color = Color.blue;

现在应该是:

cube.GetComponentInChildren<Renderer>().material.color = Color.blue;