- Home /
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 ='
Answer by DeathDev · Nov 08, 2015 at 03:09 AM
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. :)
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.");
}
}
}
Thank you, it worked. It's kind of weird that unity has Js scripts in C# docs.
Anyways, now I encountered a different problem. GameObjects with Enemy01 tag still don't get added to the array. As soon as I start the Scene, the GameObject with this script gets deleted and I get the Debug.Log ("Enemies array has no enemies in it.");
These are the errors I get:
UnityException: Tag: Enemy01 is not defined.
DoorOpen.Start () (at Assets/DoorOpen.cs:9)
NullReferenceException: Object reference not set to an instance of an object
DoorOpen.Update () (at Assets/DoorOpen.cs:20)
Answer by Graham-Dunnett · Nov 07, 2015 at 02:58 PM
Your line 7 is written in Javascript, but the file is c#.
Answer by himanshugupta159 · Jan 22, 2019 at 06:38 AM
Written a blog related to concept of varibles and function the link is attched below: https://unfragilecoding.blogspot.com/2018/04/basicsof-programming-variables-and.html