Randomly activated GUI Texture

Good day, I want to have randomly activated GUI Texture with audio for my scary game, so it might appear anytime. I’d also like to activate it multiple times during playing. Here is my script:

var jumpscare : GameObject;

function Start () {
var randomPick : int = Mathf.Abs(Random.Range(1,10));
jumpscare.SetActiveRecursively(false);
InvokeRepeating("ScareMe", 1, randomPick);
}

function ScareMe () {
audio.Play();
jumpscare.SetActiveRecursively(true);

yield WaitForSeconds (0.5);
jumpscare.SetActiveRecursively(false);
}

I tried to make it as simple as I could (I even used GameObject for my GUITexture), but I still can’t see my mistake… any advice?

Thanks a lot.

InvokeRepeating does not work with coroutines. You can test it by removing the yield from your code.

You can do what you need with one additional boolean variable and coroutine:

var jumpscare : GameObject;
var isScareActive : boolean;

function Start () {
	var randomPick : int = Mathf.Abs(Random.Range(1,10));
	jumpscare.SetActiveRecursively(false);
	isScareActive = true;
	ScareMe(randomPick);
}
 
function ScareMe (randomPick : int) {
	while(isScareActive)
	{
		jumpscare.SetActiveRecursively(true);
		yield WaitForSeconds (0.5);
		jumpscare.SetActiveRecursively(false);
		yield WaitForSeconds(randomPick);
	}
}

Scaring will continue unless isScareActive will be set to false. The only thing I skipped is initial delay, but this should be easy to implement.