Search Unity

Array of materials?

Discussion in 'Scripting' started by brewthom, Oct 3, 2019.

  1. brewthom

    brewthom

    Joined:
    Sep 1, 2019
    Posts:
    5
    I'm trying to make an array of materials to cycle through depending on a trigger. I have the trigger figured out but am unclear on the datatype. Would I make an array of strings and reference the names of the materials? I'm brand new to C# (but have worked a good bit in Processing) so help would be greatly appreciated. Thanks in advance.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You can make and use an array like this:
    Code (csharp):
    1. public Material[] materials;
    2. private int currentMat = 0;
    3.  
    4. void Update() {
    5. if (Input.GetKeyDown(KeyCode.Space) ) { //or whatever your trigger is
    6. currentMat = (currentMat + 1) % materials.Length;
    7. GetComponent<Renderer>().material = materials[currentMat];
    8. }
    9. }
     
  3. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    And if you make just about any Unity type public, such as a Material, you can drag the materials straight into the Inspector slots it will make for you. Clicking the slot will even "pulse" the real asset.

    You could use save names and use Resources.Load("assetName") to grab the materials, which is what I think you were suggesting, but making Inspector links is almost always easier.