- Home /
How do I get a function to recognize a variable in function Update()
//SCRIPT GOAL
//every 10 seconds pick a location,move to it and then patrol
var ready : boolean;
var speed : float;
var timer : float;
var patrolTimer : float = 10; //how long should it patrol for
//Targets
var target1 : Transform;
var target2 : Transform;
var target3 : Transform;
var target4 : Transform;
function Update (){
if(ready == true){
patrolTimer = 10;
//pick location
var chooseNext = Random.Range(0,2);
//countdown to move
timer -= Time.deltaTime;
if(timer <= 0){
ready = false;
}
}
if(ready == false){
Move();
}
}
function Move(){
var step = speed * Time.deltaTime;
if(chooseNext == 0){
Debug.Log("moving");
// move towards target1
transform.position = Vector3.MoveTowards(transform.position, target1.position, step);
if(this.gameObject.transform.position == target1.position){
Patrol();
Debug.Log("Reached destination 1");
}
}
if(chooseNext == 1){
Debug.Log("moving");
// move towards target1
transform.position = Vector3.MoveTowards(transform.position, target2.position, step);
if(this.gameObject.transform.position == target2.position){
Patrol();
Debug.Log("Reached destination 2");
}
}
if(chooseNext == 2){
Debug.Log("moving");
// move towards target1
transform.position = Vector3.MoveTowards(transform.position, target3.position, step);
if(this.gameObject.transform.position == target3.position){
Patrol();
Debug.Log("Reached destination 3 ");
}
}
}
function Patrol(){
//patrolling
Debug.Log("patrolling");
patrolTimer -= Time.deltaTime;
if(patrolTimer <=0){
//finished patrolling
ready = true;
Timer = 1;
Debug.Log("Ready to move");
}
}
Debugger keeps giving unknown identifier : chooseNext. I want chooseNext to change everytime ready becomes true so I can't put it into move() otherwise the ready = false function would keep calling it andd the object would spaz out deciding where to go. How can I get the function Move() section to get the chooseNext variable from update().
Thanks in advance Stealth
Answer by NoseKills · Dec 28, 2014 at 01:33 AM
You make it a "field" instead of a local variable, i.e. you move it outside the Update() like your other variables. Then it's visible in the whole script.
var chooseNext : int;
function Update ()
{
if(ready == true)
{
patrolTimer = 10;
//pick location
chooseNext = Random.Range(0,2);
//countdown to move
timer -= Time.deltaTime;
if(timer <= 0)
{
ready = false;
}
}
if(ready == false)
{
Move();
}
}
Also, I don't know what exactly you want to happen in this script and i don't know what the start values for time
and ready
are but to me it looks like that when Patrol()
finishes for the first time, the next entire second you spend in the if(ready == true)
randomising the chooseNext
etc...
Hey thanks man! Thats exactly what I want to happen. The script worked. Thanks again!