How can I make that everyTime I change the texture of material, it won't change texture of every Instantiated Object that has that material

Hello.

I have a prefab called Cube, and I am instantiating at the mouse position (onClick). But before that I have a small panel with different types of textures. After I click on one of this texture, I access the material that the cube has, and change it’s _MainTexture.

using UnityEngine;
using System.Collections;

public class AssignMaterial : MonoBehaviour {
	
	private static Vector3 size;
	private Renderer s;
	public Texture newTexture;
	private Material material;
	public string materialName;
	//rayCast.transform.GetComponent<Renderer>().material.SetTexture("_MainTex", newTexture);
	// Use this for initialization
	void Start () 
	{
		size = transform.localScale;
		material = Resources.Load("Materials/" + materialName) as Material;
	}
	
	// Update is called once per frame
	void Update () 
	{

	}

	public void OnClickDown()
	{
		material.SetTexture ("_MainTex", newTexture);
		Debug.Log (material.name);
		transform.localScale = new Vector2(0.75f, 0.75f);
	}

	public void OnClickUp()
	{
		transform.localScale = size;
	}
}

This script is assigned to the specific Image(texture) in the panel I have created.

Now for example I have texture A and B, so first I click on texture A so this texture A will be assigned on the material, and when I instantiate a Cube it’s texture will be A. That works perfect. Now when for example if I click on texture B so now the material will have texture B (good), but the problem is that the texture of the Cube instantiated before will also have now texture B. So from Texture A->B.

How can I make so that every Cube will have it’s own texture. Shell I duplicate the material every time I instantiate a cube or shell I still use the same material for all of the Cubes but with some kind of hacks.

Hope you guys will help me. Please if you have some questions please ask.

Hi,

I think you can use the Renderer component on your GameObject insteed of changing the Texture on your generic Material.

private Renderer _renderer;
public Texture newTexture;

void Start() {
  _renderer = GetComponent<Renderer>();  
}

public void OnClickDown()
{
    _renderer.material.mainTexture = newTexture;
}

Instead of changing the material that you load using Resources.Load, you want to use the material that the renderer component uses. In the renderer component, there is a distinction between material and sharedMaterial.

Changing material.SetTexture to GetComponent().material.SetTexture should work.