- Home /
One key to switch between two materials??
I have a table that switches from the standard texture to another texture (redTex) when I tap the screen on the smartphone. My question is, how can I get it to switch back to the standard texture, when I tap again??
Here's my script:
var redTex : Texture2D;
function Update () {
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
renderer.material.mainTexture = redTex;
}
}
Answer by robertbu · Jun 04, 2013 at 04:21 PM
Try this:
var tex : Texture2D;
function Update () {
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
var texT = renderer.material.mainTexture;
renderer.material.mainTexture = tex;
tex = texT;
}
}
If all of your materials get the same texture like this example, then you can just extend the code:
var tex : Texture2D;
function Update () {
if (Input.touchCount == 1)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
var texT = renderer.materials[2].mainTexture;
renderer.materials[2].mainTexture = redTex;
renderer.materials[3].mainTexture = redTex;
renderer.materials[4].mainTexture = redTex;
tex = texT;
}
}
But if you get into a situation where each of the materials has unique texture, or if you have to swap between more than two materials, then do as @Graham Dunnett suggests and move to an array model to store and manipulate the textures. Note if the number of materials vary or if the number materials is large, use a 'for' loop to make the exchange.
Works with multiple textures as well! Thanks!! Would you $$anonymous$$d giving me a quick explanation/walk-through of how the script works exactly??..I'm using this for my exam project and Javascript is still very new to me.
Since all the materials are set to the same texture, first we grab a reference to the the current texture from one of the materials and put it in the variable 'texT'. Next we assign the texture 'tex' to all the materials. Finally we set 'tex' to the old texture, so that the next time the code is executed we will have the old texture to use.
Can you also post the c# code for this code? Thank you