Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in 'Scripting' started by matias-e, Sep 10, 2015.

  1. matias-e

    matias-e

    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:
    38,520
    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.