Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Removing a material from a list by referring to a GameObject's material

Discussion in 'Scripting' started by Kinkku2, Sep 10, 2015.

  1. Kinkku2

    Kinkku2

    Joined:
    Sep 29, 2014
    Posts:
    106
    Heya! So I'm trying to remove a material from a list by referring to a GameObject's material. The list includes the material the GameObject has, as the material for the GameObject is infact given from the list. However, when I refer to the GameObject's material in an attempt to remove it from the list, this does not work. Here's the code:

    Code (CSharp):
    1. void Start () {
    2.     materials.Add (blue);
    3.     materials.Add (yellow);
    4.     materials.Add (green);
    5.  
    6.     midRend = middleCube.GetComponent<MeshRenderer>();
    7.     midRend.material = materials[Random.Range(0, materials.Count)];
    8. }
    9.  
    10. void OnTriggerEnter2D(Collider2D col) {
    11.     int ranIndex;
    12.     Material save;
    13.     if(col.tag == "MiddleCube") {
    14.         save = midRend.material;
    15.         materials.Remove(save);
    16.  
    17.         ranIndex = Random.Range(0, materials.Count);
    18.         midRend.material = materials[ranIndex];
    19.  
    20.         //materials.Add(save);
    21.    }
    22. }
    What could be of help here? It seems as if the material I'm plugging into the middle cube is actually an instance and not the actual material, so I think this might be the problem. How could I make it not an instance? Thanks.
     
    Last edited: Sep 10, 2015
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    8,397
    I believe there is a Renderer.sharedMaterial you can set instead, that won't instance it at assignment time. Check the docs for something along those lines.
     
unityunity