Replacing materials in an array

I’m trying to be able to toggle object highlights on and off. Some objects have one material and others have multiple. I’ve been reading a bunch of threads on here and tried a bunch of different thing but I can’t seem to make this work.

    private bool highlighted;
    public Material outlineMat;

    void Start ()
    {
        Material[] originalMats  = new Material[gameObject.GetComponent<MeshRenderer>().materials.Length];
        originalMats = gameObject.GetComponent<MeshRenderer> ().materials;
        Material[] highlightMats  = new Material[gameObject.GetComponent<MeshRenderer>().materials.Length];
        for (int i = 0; i < highlightMats.Length; i++) {
            highlightMats [i] = new Material (outlineMat);
        }
        highlighted = false;
    }

    void Update (){
        if (Input.GetKeyDown (KeyCode.Space)) {
            if (highlighted) {
                gameObject.GetComponent<MeshRenderer> ().materials = originalMats;
                highlighted = false;
            } else {
                gameObject.GetComponent<MeshRenderer> ().materials = highlightedMats;
                highlighted = true;
            }
        }
    }
}

Can someone tell me where I’m going wrong? Also, can you tell me the difference between Material and UnityEngine.Material? I seem to be running into problems with that but I don’t really know what that is.

Thanks so much.

There shouldn’t be one, I don’t think, unless you’ve named one of your scripts “Material”.

I think your main issue in this code is that you’re declaring originalMats and highlightedMats inside Start(), so they’re local to that function. Move their declaration outside the function (like “highlighted” and “outlineMate” are), and that should help you.

1 Like

I owe you a beer, StarManta. You are correct on both fronts. Thank you so much!

Cider, please :smile: