- Home /
Set npc to inactive when certain distance away from controller (script not working)
Hello - when an npc walks past my character controller: when he is a certain distance away from the character controller , I want the npc to be set to inactive and another npc to be instantiated in the same position. After three seconds I want this second npc to be set to inactive, and the first npc to be set to active in the new position.
The problem I have is that although I can set the characters to active in the right position - the range part of my script doesn't seem to be working - and when my character controller walks up to the npc - he isn't set to inactive.
Could you tell me what's wrong with my script? (JavaScript)
var player : GameObject;
var dan : GameObject;
var exoGrey : GameObject;
var characterPosition : Vector3;
var range : float = 4;
function Start () {
dan.SetActive (false);
exoGrey.SetActive (false);
}
function OnTriggerEnter () {
dan.SetActive (true);
var distance = Vector3.Distance(player.transform.position, transform.position);
if (distance <= range){
characterPosition = dan.transform.position;
dan.SetActive (false);
exoGrey.SetActive (true);
exoGrey.transform.position = characterPosition;
exoGrey.transform.Rotate (new Vector3(0, 180, 0));
yield WaitForSeconds (3);
characterPosition = exoGrey.transform.position;
exoGrey.SetActive (false);
dan.SetActive (true);
dan.transform.position = characterPosition;
}
}
Thanks so much, Laurien
Why don't you set the radius of your collider to equal the distance that you want it to trigger at? That would alleviate the distance check. And what is supposed to be set to active when you enter the trigger? The code says exo grey will be active for 3 seconds, and then Dan will be left active thereafter.
Thanks - I've attached a collider to Dan ins$$anonymous$$d with this script attached to it. But although he is set to inactive when the player hits Dan's collider, and exo grey is set to active. The yield WaitFor Seconds doesn't work, and exo grey isn't set to inactive for some reason. Do you know why?
var player : GameObject;
var dan : GameObject;
var exoGrey : GameObject;
var characterPosition : Vector3;
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;
}
Are you sure that there are no errors in your console? I bet the yield does work through, because it works everywhere else in unity on everyone else's machine. ;) try adding a debug.log statement in your code after your yield to see if it prints out. Learning to debug your code is more important to being a successful programmer than learning how to code in the first place.