louis12356 louis12356 - 3 months ago 31
C# Question

Add a component (Material) to a cube in unity C#

I am trying to add a component (material) to a number of cubes.
I got an array of cubes and they have to get painted then. After the first cube Unity throws an error that says:


MissingComponentException: There is no 'Material' attached to the
"Cube" game object, but a script is trying to access it


My code:

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameScene : MonoBehaviour {

SceneManager Changer;
public Scrollbar speed, size;
GameObject[,] cubes;
int sizer;
Color mixer;

// Use this for initialization
void Start () {
size.value = PlayerPrefs.GetFloat("sizeSecond");
speed.value = PlayerPrefs.GetFloat("speed");

SetSize();

cubes = new GameObject[sizer, sizer];

GenerateCubes();

mixer = new Color(PlayerPrefs.GetFloat("red"), PlayerPrefs.GetFloat("green"), PlayerPrefs.GetFloat("blue"));


}

// Update is called once per frame
void Update () {

}

public void GoBack() {
SceneManager.LoadScene(2);
PlayerPrefs.SetInt("chosenScene", 1); //key setzen
PlayerPrefs.SetFloat("speed", speed.value);
PlayerPrefs.SetFloat("sizeSecond", size.value);
}

void SetSize() {
if (PlayerPrefs.GetInt("size") == 0)
{
sizer = 20;
}
else if (PlayerPrefs.GetInt("size") == 1)
{
sizer = 40;
}
else if (PlayerPrefs.GetInt("size") == 2)
{
sizer = 60;
}
}

void GenerateCubes() {
for (int i = 0; i < sizer; i++)
{
for (int j = 0; j < sizer; j++)
{

cubes[i, j] = GameObject.CreatePrimitive(PrimitiveType.Cube); //erzeugen
cubes[i, j].transform.position = new Vector3(i -sizer / 2, j - sizer / 2, 0); // durch 2 damit es mittig angezeigt wird.
cubes[i, j].GetComponent<Material>().color = mixer;

Instantiate(cubes[i, j]);
}
}
}


}

sizer gets the amount of cubes.

Answer

When you generate cube with GameObject.CreatePrimitive(PrimitiveType.Cube);, a cube is created with a Mesh Renderer attached to it not Material.

enter image description here

You can access the Material of the cube from the Mesh Renderer component.

Simply Replace

cubes[i, j].GetComponent<Material>().color = mixer;

with

cubes[i, j].GetComponent<MeshRenderer>().material.color = mixer;