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.

2 Answers

2

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 Material Material1; //in the editor this is what you would set as the object you wan't to change public Renderer Object; void Start() { Object.material = Material1; } There are more renderers besides MeshRenderers. Using Renderer will allow any class that is derived from Renderer to be assigned.

To be more general, Object.GetComponent<MeshRenderer> could be Object.GetComponent<Renderer>

What if the Mesh renderer has 3 elements for materials?

See here: https://answers.unity.com/questions/1373364/how-to-change-object-material-via-script.html