- Home /
How do I change the texture of a gameobject only while a touch is on it on iOS?
I have buttons that aren't using the GUI system, but instead are just textures on gameobjects. I'm using raycast.hit to detect whether the button is hit. I want the button to swap textures while a touch is on it to give the visual effect of being pressed down. I haven't been able to get the picture to switch back to it's original when the touchphase ends.
function Update(){
if (fingerCount>0||Input.GetMouseButtonDown(0)) {
var raybutton: Ray;
if ((fingerCount>0)&&(Input.GetTouch(0).fingerId==0)&&(Input.GetTouch(0).phase==TouchPhase.Began)){
raybutton= OrthoCam.ScreenPointToRay(Vector3(Input.GetTouch(0).position.x,Input.GetTouch(0).position.y));
}
var hitbutton: RaycastHit;
if (Physics.Raycast(raybutton, hitbutton)) {
var buttonName=hitbutton.transform.gameObject.name;
if (buttonName=="Restart"){
GameObject.Find("Restart").renderer.material.mainTexture=Resources.Load("RestartPressed");
var restartflag=true;
}
}
for (var touch = 0; touch < Input.touchCount; ++touch) {
if (Input.GetTouch(touch).phase == TouchPhase.Ended||Input.GetTouch(touch).phase == TouchPhase.Canceled) {
if(restartflag==true){
GameObject.Find("Restart").renderer.material.mainTexture=Resources.Load("Restart");
restartflag=false;
}
}
}
}
Answer by mattssonon · Nov 14, 2013 at 09:53 AM
If you initialize restartFlag
inside an if conditional, it won't exist outside of that if conditional, so when you reach if (restartFlag)
that variable does not exist anymore. You need to initialize it outside of Update()
if you want its state to persist between calls to Update()
.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121849im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Problems while setting up buttons on the GUI 0 Answers
How will i develop the type of gui? 0 Answers
iphone album art how? 0 Answers
Unity GUI text displaying as noise 1 Answer