- Home /
 
Change the material on an Object in a script?
How do I give a gameObject a new material when I push a button or hit a trigger? I am new to Unity.
I managed the trigger but not the material change. I don't even know how to put my materials in an array to cycle through them.
To be clear I want to use two different materials I edited in the project tab and assign them to an object in my game according to a parameter. The object is a plane(not aircraft) that moves on the x-y-plane and displays a picture of a soldier holding a rifle moving on the x-y-plane, when he hits a trigger he changes his direction and should change his material or the x-value on the active material. It is for a 2D platformer like Mario. I managed to move him and let him change directions (basicly move backwards) but I want to have the picture from the other side so that the soldier is always facing in the direction he walks.
Sorry for the confusing sentence, I am not a native English speaker so bear with me.
Answer by novahavocyt · Mar 15, 2018 at 10:35 PM
Hi! If you still need help with this I may be a little help. Here is some code I wrote. Hope it helps you!
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;
 
 public class PlayerMaterialSwaper : MonoBehaviour {
    
     public Material Material1;
     //in the editor this is what you would set as the object you wan't to change
     public GameObject Object;
 
     void Start()
     {
          Object.GetComponent<MeshRenderer> ().material = Material1;
     }
 {
 
              Why don't you just declare your "Object" variable as "Renderer"?
  public $$anonymous$$aterial $$anonymous$$aterial1;
  //in the editor this is what you would set as the object you wan't to change
  public Renderer Object;
 
  void Start()
  {
       Object.material = $$anonymous$$aterial1;
  }
 
                  There are more renderers besides $$anonymous$$eshRenderers. Using Renderer will allow any class that is derived from Renderer to be assigned.
To be more general, Object.GetComponent<$$anonymous$$eshRenderer> could be Object.GetComponent<Renderer>
What if the Mesh renderer has 3 elements for materials?
If you know there's more than one renderer, then you can use Object.GetComponents<Renderer> and iterate through them, depending on what you want to achieve. 
Your answer
 
             Follow this Question
Related Questions
Change Materials On Button Press or Hold? 1 Answer
Change material GameObject locally 1 Answer
Player Material Change works on shop preview menu, does not change Player material on other scenes. 0 Answers
Changing gameObjects material on trigger? 1 Answer
How to change material of gameobject using C# to a material asset. 2 Answers