Swapping Materials and Textures

From ETC Public Wiki
Jump to: navigation, search

If you want to change the rendered appearance of an object, you need to either swap its Renderer's material, or to modify the Material itself. See below for information on how to do either:

Material Swapping

You can change what material an object uses to render simply by reassigning the material property of its Renderer. There are two ways to choose which Material you want swap to: you can access a reference to the Material (such as a member-variable), or you can load it from a Resources folder. The example below shows an object that will swap its material to an alternate Material after 5 seconds by using a public member-variable as a reference to the alternate Material:

public class NewBehaviourScript : MonoBehaviour {
	
	public Material alternateMaterial;

	void Start() {
		
	}
	
	void Update () {
		if (Time.time > 5)
		{
			renderer.material = alternateMaterial;
		}
	}
}

Note that this script will not work correctly unless the alternateMaterial property has a Material drag-and-dropped onto its field in the editor (or is otherwise assigned before it is needed).

As mentioned above, and alternative method is to make use of a Resources folder: by placing the appropriate Material in a folder named "Resources" within the asset folder of your project, you can dynamically load and access that Material by name. Example:

public class NewBehaviourScript : MonoBehaviour {
	
	private Material alternateMaterial;

	void Start() {
		alternateMaterial = Resources.Load("alternateMaterialAsset") as Material;
	}
	
	void Update () {
		if (Time.time > 5)
		{
			renderer.material = alternateMaterial;
		}
	}
}

Note that the only difference between this example and the last is that alternateMaterial property is made private, and that it is assigned during Start via Resources. For more on information on Resources, see its Script Reference: http://unity3d.com/support/documentation/ScriptReference/Resources.html

Texture Swapping

To swap the texture of a Material on the fly, you can use the SetTexture function to set what Texture (or textures, if it has multiple) it references. Note that, like with swapping a Material, you need some way of saying which specific texture you wish to use; again, you can either use a reference, or use Resources (see above for how to do this). Example (using a reference):

public class NewBehaviourScript : MonoBehaviour {
	
	public Texture alternateTexture;

	void Start() {
		
	}
	
	void Update () {
		if (Time.time > 5)
		{
			renderer.material.SetTexture("_MainTex",alternateTexture);
		}
	}
}

Like the above, this script waits 5 seconds, and then makes the modification. Note that depending on where and how you access the Material, this modification will only apply to the individual object, or to the Material globally. The above script will only modify the individual object.