dimanche 12 août 2018

Apply materials to every other object in Unity using code

I'm trying to spawn 8 quads in a row and then assign a material to every other quad, so it would look like a checkerboard pattern. The code I have accomplishes that, but I was wondering if there was a way to simplify it. So if I were to create more quads in different positions (for example, I wanted to create a row above the one I've already created), I wouldn't have a long list of repetitive code.

    for (i = 0; i < 8; i++)
    {
        GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
        quad.transform.position = new Vector3(i * 1, 0, 0);

        if (i == 1)
        {
            MeshRenderer mesh = quad.GetComponent<MeshRenderer>();
            mesh.material = (Material)Resources.Load("Charcoal");
        }

        if (i == 3)
        {
            MeshRenderer mesh = quad.GetComponent<MeshRenderer>();
            mesh.material = (Material)Resources.Load("Charcoal");
        }

        if (i == 5)
        {
            MeshRenderer mesh = quad.GetComponent<MeshRenderer>();
            mesh.material = (Material)Resources.Load("Charcoal");
        }

        if (i == 7)
        {
            MeshRenderer mesh = quad.GetComponent<MeshRenderer>();
            mesh.material = (Material)Resources.Load("Charcoal");
        }

        else
        {
            MeshRenderer mesh = quad.GetComponent<MeshRenderer>();
            mesh.material = (Material)Resources.Load("Bone");
        }

    }

My code checks to see if the position of the quad is equal to 1, 3, 5 or 7, and applies my material, then it uses another material of mine to fill the quads that aren't in those positions.

Aucun commentaire:

Enregistrer un commentaire