How to make a random occurrences using a timer?

The game I’m making is mostly about randomization, you enter the scene, a random texture appears on an object, here is the code but it changes every second, I want it to change every time you enter the scene, if I get rid of yield and press play, unity goes grey and crashes.

#pragma strict

var textures: Texture2D[]; // assign some textures in the Inspector
 
function Start (){
    while (true){
        renderer.material.SetTexture ("_MainTex", textures[Random.Range(0, textures.Length)]);
        yield WaitForSeconds(2.0);
    }
}

I also want it so when you enter a scene a random number is chosen and then it begins to count down to 0 before ending the game. When I press play the random number is placed, then it goes straight to 0 instead of counting down from said number. I hope this is not too much to ask i’m fairly new.

#pragma strict

var timer : int;

function Start () 
{
	timer = Random.Range(10.0, 20.0);
}

function Update ()
{
	timer -= Time.deltaTime;
	Debug.Log(timer);
	
	if(timer <=0)
	{
		timer = 0;
	}
}

Problem One: Don’t use while loops, they’ve been known to crash Unity hard.

Problem Two:
For the random events try this…

var nextTime: float;
var modifier : float;

function Start()
{
    nextTime = 0.0;
}

function Update()
{
    //Get a random value
    modifier = Random.Range(10.0,20.0);
    
    //Set nextTime equal to current run time plus modifier
    nextTime = Time.time + modifier;

    //Check if current system time is greater than nextTime
    if(Time.time > nextTime)
    {
        //DO EVENT
    }
}

To help solve the timer going straight to 0, start by making it a float instead of an int.

To help with the texture issue, simply remove the “while(true)” part. With it there, you are attempting to change the texture every frame, and you’ll never leave the start method!

while (true)

That’s an infinite loop. It never ends.

If your code runs asynchronously (such as a coroutine), that’s okay because the program will be able to run while the coroutine is paused.

When you delete all yield statements in a function, it’s no longer a coroutine. The loop was always infinite; the only difference now is that it keeps control of the main thread, too.

Infinite loop + blocking main thread = your program stops running.