Find Game Objects With Tag

I have 4 ghosts chasing my player. If one of them collides with my player then all of the ghosts will go back to their base and i will lose a life. The problem is sometimes not all of my ghost will return. here’s my code:

static var scores:int;
var monsters;
var lives:int;
lives=3;
function Update(){
	if(gameObject.transform.position.x>=28)
		transform.position=Vector3(-28,1,2);
	else if(gameObject.transform.position.x<=-28)
		transform.position=Vector3(28,1,2);
	if(lives==0)
		Application.Quit();
}
function OnTriggerEnter(ghost:Collider){
	if(ghost.gameObject.tag=="Ghosts"){
		lives--;
		monsters=GameObject.FindGameObjectsWithTag("Ghosts");
		for(var monster in monsters){
			monster.GetComponent(NavMeshAgent).Stop(true);
			monster.transform.position=Vector3(0,0.7,8);
		}
		transform.position=Vector3(0,1,-16);
	}
}
function OnGUI(){
	GUI.Label(Rect(0,0,255,28),"Score: "+scores);
	GUI.Label(Rect(0,29,255,28),"Lives: "+lives);
}

Note: Application.Quit(); doesnt work either.

Application.Quit() maybe works only after built it… using the exe. If you press play on Unity it doesn’t work.
Try to do it :slight_smile:

I think you should add boolean in your GhostScript:

   private bool chasingPlayer;
    
    void Start() {
     chasingPlayer = true;
     // Here will be other things for start
    }
    

    void Update() {
    if (chasingPlayer) {
    // chasing player algorithm
     } else {
     // going back to base
     }
    }

public void goBack() {
   chasingPlayer = false;
}

After that in your PlayerScript you will write this:

    function OnTriggerEnter(ghost:Collider){
        if(ghost.gameObject.tag=="Ghosts"){
           lives--;
           monsters=GameObject.FindGameObjectsWithTag("Ghosts");
           for(var monster in monsters){
             GhostScript script = monster.GetComponent<GhostScript>();
             script.goBack();
           }
           transform.position=Vector3(0,1,-16);
        }
    }

That how I do.