Need help with a script I wrote that randomly applies materials to an object.

So basically I have this script that randomly applies a material to an object from a list of materials. Now I have several of the same object in my scene and I want to apply the same randomly selected material to all objects.The way I tried doing this was by having a master object that has the random material script on it and having a script on the other objects that takes the material from the master object and applies it to those other objects but it doesn’t actually work. Here are my 2 scripts:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class MaterialRand : MonoBehaviour
{
    //GameObject we are applying our material to
    public GameObject matObj;

    //The Materials we will be selecting from
    public Material mat01;
    public Material mat02;
    public Material mat03;
    public Material mat04;
    public Material mat05;

    //Final Material
    [HideInInspector]
    public Material finalMat;

    void Start()
    { 

       
       //Creates a list of materials we will be randomly selecting from
       var matList = new List<Material> {mat01, mat02, mat03, mat04, mat05};
   
       //randomly select from our list of Materials
       int index = Random.Range(0, matList.Count - 1);

       //Set our final material
       finalMat = matList[index];

       //assign our selected material to our object
        matObj.GetComponent<MeshRenderer>().material = finalMat;
    }
}

and the one that applies the material to the other objects:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class setChildMat : MonoBehaviour
{
    //Object to draw material from
    public GameObject MasterObject;
    //Object to set material to
    public GameObject ChildGameObject;
   
    public Material Material1;

    // Start is called before the first frame update
    void Start()
    {
        //Set the master game object's material to be the material of the child game object
       Material1 = MasterObject.GetComponent<MeshRenderer>().material;
       ChildGameObject.GetComponent<MeshRenderer>().material = Material1;
    }

}

as you can see I am attempting to set the material of the mesh renderer on the first object to the material of the mesh renderer of the second object but when I do that it simply takes the default material from the first object not the randomly selelcted material.

It might be because they’re both running in start.
A quick fix might be to change your master script Start() to Awake() because Awake runs before Start

Changing the master script to Awake() did exactly what I need it to thanks!

1 Like