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?

1 Answer

1

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! :)