- Home /
on touch swap texture, wait until sound played then swap texture back
Hi all, I am using this script to swap my texture on click/touch:
private var ray : Ray;
private var rayCastHit : RaycastHit;
var mySound: AudioClip;
var myObject : GameObject;
var texture1 : Texture2D;
function Update(){
if(Input.GetMouseButtonDown(0)){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit)){
//add name of object/button to affect in ""
if(rayCastHit.transform.name == "face1"){
audio.clip = mySound;
audio.Play();
myObject.renderer.material.mainTexture = texture1;
Debug.Log ("touched face1");
}
}
}
}
and swap back on mouse button up/finger lifted off screen:
private var ray : Ray;
private var rayCastHit : RaycastHit;
var myObject : GameObject;
var texture1 : Texture2D;
function Update(){
if(Input.GetMouseButtonUp(0)){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit)){
//add name of object/button to affect in ""
if(rayCastHit.transform.name == "face1"){
myObject.renderer.material.mainTexture = texture1;
Debug.Log ("mouse button up");
}
}
}
}
At the moment when I click/touch the texture swaps and sound plays, but what I want is for the texture to swap back once the sound has finished playing.
Can anyone please give me any help on this?
Answer by Dzoni94 · Apr 29, 2013 at 06:47 PM
Something like this should do the trick. Add another variable of type Texture2D so the game knows which texture it should switch back to after the sound is played (texture2) and use the following code.
private var ray : Ray;
private var rayCastHit : RaycastHit;
var mySound: AudioClip;
var myObject : GameObject;
var texture1 : Texture2D;
var texture2 : Texture2D;
function Update(){
if(Input.GetMouseButtonDown(0)){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit)){
if(rayCastHit.transform.name == "face1"){
FaceTouched();
}
}
}
}
function FaceTouched(){
audio.clip = mySound;
audio.Play();
myObject.renderer.material.mainTexture = texture1; // Change texture on touch
yield WaitForSeconds(mySound.length); // Wait till sound is played
myObject.renderer.material.mainTexture = texture2; // Change texture to another one
}
Thankyou very much for your help, this works perfect! :)
Your answer
Follow this Question
Related Questions
Change texure on NGUI BUTTUN press 0 Answers
Assigning UV Map to model at runtime 0 Answers
Swap Custom Cursor for Animated Movie Texture or Sprite Sheet? 1 Answer
How to swap texture on object upon collision? 1 Answer
GUI.Button Texture Swap? 3 Answers