How do i add a material i made to instantiated game objects?

I have been trying to figure this out for far to long and figured id ask here. I am making a music visualizer and on start it instantiates a bunch of white cubes How do i add a material to them? I have them tagged as “cubes”

Here is a pic of the code snippet, im not sure how to just show the code here yet.

public void SpawnLine()
{
visualScale = new float[amnVisual];
visualList = new Transform[amnVisual];

for (int i = 0; i < amnVisual; i++)
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube) as GameObject;
visualList = go.transform;
visualList_.position = Vector3.right * i;_
go.tag = “cubes”;

// This changes the color, but not what im after.
// go.GetComponent().material.color = Color.green;
}
}

After creating the object, can assign material to it, see some basic example here: (takes material from array)

ps. can use code tags for scripts Using code tags properly - Unity Engine - Unity Discussions

1 Like

Ah thanks. And will that method work with objects that aren’t created until after the program starts?

Yes, just do it after its created

GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube) as GameObject;
var rend = go.GetComponent<Renderer>();
rend.material = materials[0];
1 Like

Thanks alot! worked