Script to set character to active after 3 seconds not working

Hello,

When my character controller walks into the collider around an npc: the npc is set to inactive, and a new npc is set to active in the same position. After 3 seconds I want the second npc to be set to inactive and the first npc to be set to active again in the new position.
(So in the game looking like a character walking past and for three seconds appearing as a different person)

The script works in that on collision, the first npc is set to inactive and the second npc set to active in the right position.

The problem is that after 3 seconds - he doesn’t switch back to the first character, and I can’t work out why.

This is the script (Javascript):

var player : GameObject;
var dan : GameObject;
var exoGrey : GameObject;
var characterPosition : Vector3;

function Start () {

exoGrey.SetActive (false);
dan.SetActive (true);

}


function OnTriggerEnter () {


characterPosition = dan.transform.position;
dan.SetActive (false);
exoGrey.SetActive (true);
exoGrey.transform.position = characterPosition;


yield WaitForSeconds (3);


characterPosition = exoGrey.transform.position;
exoGrey.SetActive (false);
dan.SetActive (true);
dan.transform.position = characterPosition;

}

Does anyone have any idea why?
(I’m not getting any errors in the console)

Thanks, Laurien

Big edit:

I was wrong about the return type of OnTriggerEnter. It can indeed be of type IEnumerator. I still wouldn’t recommend it though. I tried the following script:

function OnTriggerEnter () {
	Debug.Log("foo " + Time.time);
	yield WaitForSeconds(3.4);
	Debug.Log("bar " + Time.time);
}

And got:
foo 0.48
bar 3.897639
Which means the yield gets executed correctly. The reason your short example did not yield, is that you didn’t use curly brackets and thus the if statement only was relevant for the single line directly under it.

Back to your original problem.
Make sure, that the script is not on a gameObject, which gets disabled. Since it works otherwise, this is pretty much the only thing that could go wrong.