- Home /
switching textures on mouseUp (C#)
Still trying to digest C#
I have plane with a texture
when I click on it, I want the texture to change back & forth between 2 images... Simple
So I set a bool and it works (mouseUp detected) What am I doing wrong?
using UnityEngine;
using System.Collections;
public class switchTexture1 : MonoBehaviour {
public bool isButtonSelected = false;
//The Textures you wish to use for swaping ( could use a Texture2D[] if you have lots)
public Texture onTexture;
public Texture offTexture;
//The MeshRenderer of the object your trying to swap textures on
public MeshRenderer currentRenderer;
// Use this for initialization
void Start ()
{
//Find the MeshRenderer Component (could also use FindObjectOfType() )
currentRenderer = this.GetComponent<MeshRenderer>();
}
// Update is called once per frame
void Update ()
{
if(currentRenderer != null)
{
if(isButtonSelected)
currentRenderer.material.SetTexture("comikaze", onTexture);
else
currentRenderer.material.SetTexture("comikaze_Shhhh", offTexture);
}
}
void OnMouseUp()
{
if(!isButtonSelected)
isButtonSelected = true;
else
isButtonSelected = false;
}
}
Thanks in advance ~be
Answer by smallbit · Aug 12, 2014 at 06:34 AM
Do you have "comikazee" and "comikaze_Shhhh" textures defined in your shader ? If this is not your intention use mainTexture instead. SetTexture has different function.
http://docs.unity3d.com/ScriptReference/Material-mainTexture.html
Thank you smallbit !
This is the right direction
Here is the code for future ref:
using UnityEngine;
using System.Collections;
public class switchTexture2 : $$anonymous$$onoBehaviour {
public Texture texture;
public Texture texture2;
public bool isButtonSelected = false;
void On$$anonymous$$ouseUp()
{
if(!isButtonSelected)
isButtonSelected = true;
else
isButtonSelected = false;
Draw();
}
void Draw() {
if (isButtonSelected == true)
renderer.material.mainTexture = texture;
// Debug.Log("2set1");
if (isButtonSelected == false)
renderer.material.mainTexture = texture2;
// Debug.Log("1set2");
}
}
your code can be rewritten as
void On$$anonymous$$ouseUp()
{
isButtonSelected = !isButtonSelected;
Draw();
}
void Draw()
{
renderer.material.mainTexture = isButtonSelected ? texture : texture2;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613160416im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Switch code from Js to C# 1 Answer
Distribute terrain in zones 3 Answers
Set boolean to false when animation changes? 1 Answer
Saving drop down menu selection 1 Answer