Script dosn't work

Why this script dosn’t work? :frowning:

using UnityEngine;
using System.Collections;
 
public class Luci4: MonoBehaviour {
 
    public Material material1;
    public Material material2;
 
 
    void Start () {
 
       renderer.material = material1;
 
    }
 
    void Update () {
 
       if (Input.GetKeyDown (KeyCode.Alpha4))
       {
         if (renderer.material != material1)
 
         {
          renderer.material = material1;
 
         }
 
         else
 
         {
          renderer.material = material2;
 
         }
 
       }
 
    }
}

There are instances where Unity generates a new material instance. I’m guessing that assigning a new material is one of them. That means that line 20 will always evaluate to false. A brute force solution would be to save the current material yourself for comparison:

using UnityEngine;
using System.Collections;

public class Bug25c : MonoBehaviour {
	
	public Material material1;
	public Material material2;
	public Material currMaterial;
	
	void Start () {
		renderer.material = material1;
		currMaterial = material1;
	}
	
	void Update () {
		
		if (Input.GetKeyDown (KeyCode.Alpha4))
		{
			if (currMaterial != material1)
			{
				Debug.Log ("One");
				renderer.material = material1;
				currMaterial = material1;
			}
			
			else
				
			{
				Debug.Log ("Two");
				renderer.material = material2;
				currMaterial = material2;
			}
		}
	}
}

A cleaner solution is to use an array. You have to initialize the size of the array in the inspector, and then fill in the slots:

using UnityEngine;
using System.Collections;

public class Bug25c : MonoBehaviour {
	
	public Material[] myMaterials;

	public int curr = 0;

	void Start () {
		renderer.material = myMaterials[curr];
	}
	
	void Update () {
		
		if (Input.GetKeyDown (KeyCode.Alpha4))
		{
			curr = (curr + 1) % myMaterials.Length;
			renderer.material = myMaterials[curr]; 
		}
	}
}

Note for future questions, it is helpful if you include a title that represents the problem and a description of what the code is doing or not doing.