Declaring a variable in Start funciton

I’m following the unity documentation and I found exactly what I was looking for. The sample script in the documentation is
// Search for game objects with a tag that is not used

    function Start () {
        var gos : GameObject[];
        gos = GameObject.FindGameObjectsWithTag("fred"); 
  
        if (gos.length == 0) {
            Debug.Log("No game objects are tagged with fred");
        }
}

I did pretty much the same thing.

using UnityEngine;
using System.Collections;

public class DoorOpen : MonoBehaviour {

	void Start () {
		var enemies : GameObject[];
		enemies = GameObject.FindGameObjectsWithTag("Enemy01");

	} 

	void Update () {

		if (enemies == null || enemies.Length == 0) {
			Destroy (this.gameObject);
			Debug.Log ("Enemies array has no enemies in it.");
		}

		if (enemies.Length > 0) {
			Debug.Log ("Enemies array has enemies in it.");
		}
	}
}

However, this doesn’t work. I get this error. Assets/DoorOpen.cs(7,29): error CS1525: Unexpected symbol :‘, expecting )', ,’, ;', [', or ='

There are two problems with this script.
1) Line 7 is written in JavaScript. It should instead be:

GameObject[] enemies;

2) enemies is only defined inside of the start function, however you seem to want to access it outside of the function. To do this you will need to first declare the variable outside of any function.
Here’s a fixed version of the script. :slight_smile:

using UnityEngine;
using System.Collections;
 
public class DoorOpen : MonoBehaviour {
 
    GameObject[] enemies;   //Note - outside of any function.

    void Start () {
        enemies = GameObject.FindGameObjectsWithTag("Enemy01");
 
    } 
 
    void Update () {
 
        if (enemies == null || enemies.Length == 0) {
            Destroy (this.gameObject);
            Debug.Log ("Enemies array has no enemies in it.");
        }
 
        if (enemies.Length > 0) {
            Debug.Log ("Enemies array has enemies in it.");
        }
    }
}

Written a blog related to concept of varibles and function the link is attched below:

Your line 7 is written in Javascript, but the file is c#.