C# how to attach a material to a gameobject?

A prefab I made contains a Sphere gameobject. When I look at the prefab in the inspector the material for the sphere is grayed out and I can’t drop a texture on it.

After I instantiated the prefab in C# I want attach a material to this gameobject in c#.

Once I instantiate the material (in C#) what is the code (c#!) to then attach a material to the game object?

I’ve looked for some code samples but don’t see a consistent answer.

Thanks for any help.

(side questions, why is the material on the Sphere gameobject grayed out? If it is not there how does Unity know to show it? Is it a “public” variable of some sort that is part of the gameobject? The how did they get the complex UI for it? Is this just Unity knowing a sphere needs a material? sorry, rambling…)

the gameobject should have a renderer on it. You can change the main text on the renderer.

// pseudo code

public Texture texture; // assign in inspector, this is a field.

GameObject go = Instantiate(somePrefab, someTransform, someRotation);
go.renderer.material.mainTexture = texture;

Side questions:

The color is greyish white because of the default Mesh Renderer(you can see it in the inspector have you select it) has a material of Default-Diffuse which is colored this way. You can change it in code if you wish using:

go.renderer.material.color = Color.blue;