I am new to Unity and I am having some trouble. I am creating a role playing scene where there are 2 quads and each has a separate 2d image of a character. At a certain point in the script I change a variable and when this changes I want the material to change one quad at a time. I tried using this script and put my alternateMaterial in the Resources folder:
public Material alternateMaterial;
renderer.material = alternateMaterial;
and while this does not give me an error, it just simply does not work. What am I doing wrong? Is there a way to assign the object multiple materials and just swap which material is shown?
Thanks in advance!
if I want to assign potentially multiple different materials to the same object, or even different materials to different objects. instead of having to track down each and every object that needs to have their materials switched out (tedium in large scenes). I create a static MaterialRepo class that can be called, and used to assign to any object. then I just have a script on the object that needs its material to change just reference the MaterialRepo.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MaterialRepo : MonoBehaviour {
public List<Material> mats;
public static MaterialRepo inst;
// Use this for initialization
public void Awake () { if(inst == null){ inst = this; } }
// Update is called once per frame public void Update () { }
public Material GetMat(string _name){
if(mats != null && mats.Count > 0 && _name != null && _name != ""){
foreach(Material mat in mats){ if(mat.name == _name){ return mat; } }
}
return null;
}
public Material GetMat(int _index){
if(mats != null && mats.Count > 0 && _index >= 0 && _index < mats.Count){
return mats[_index];
}
return null;
}
public Texture GetTex(string _name){
if(mats != null && mats.Count > 0 && _name != null && _name != ""){
foreach(Material mat in mats){ if(mat.name == _name){ return mat.mainTexture; } }
}
return null;
}
public Texture GetTex(int _index){
if(mats != null && mats.Count > 0 && _index >= 0 && _index < mats.Count){
return mats[_index].mainTexture;
}
return null;
}
}
then when I want an object to get a material from the repo while maintaining a reference to their previous one I can just have it do so by:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Renderer))]
public class MatChangeExample : MonoBehaviour {
public int desiredMat;
public bool useMat1;
private Renderer _rend;
private Material mat0;
private Material mat1;
// Use this for initialization
void Start () {
_rend = renderer;
mat0 = _rend.material;
mat1 = MaterialRepo.inst.GetMat( desiredMat );
}
// Update is called once per frame
void Update () {
if(useMat1 == true && _rend.material != mat1){
_rend.material = mat1;
}else if(useMat1 == false && _rend.material != mat0){
_rend.material = mat0;
}
}
}