How do you add a material and change the size in Mesh Renderer in C# scripting?

I have written this code to generate a procedural cube Sphere.

However I am having some trouble adding materials to the Mesh Renderer via c# scripting.

Can someone please explain to me how to add a material and add/change it’s element size in the mesh renderer via scripting?

Here is my script and it fails to produce the material I want.

public class CubeSphere : MonoBehaviour {

public float radius = 50f;

public int gridSize = 10;

private Mesh mesh;
private Vector3[ ] vertices;
private Vector3[ ] normals;
private Color32[ ] cubeUV;

public Material Planet = Resources.Load(“Planet”, typeof(Material)) as Material;

private void Awake () {
Generate();
}

private void Generate() {
GetComponent().mesh = mesh = new Mesh();
GetComponent().sharedMaterial = Planet;

mesh.name = “Procedural Sphere”;
CreateVertices();
CreateTriangles();
CreateColliders();
}

Please use code tags.

If you haven’t seen it before, check out the Unity - Scripting API:, which can answer many questions like these very quickly.

In this case, setting multiple materials to a mesh renderer is very easy:

Material[] materials = YourOwnMethodThatReturnsAnArrayOfMaterials();
var rend = GetComponent<MeshRenderer>();

rend.materials = materials;