- Home /
The question is answered, right answer was accepted
[SOLVED] Problem with "foreach".
I'm making script that'll select nearest object with tag. It's this:
using UnityEngine;
using System.Collections;
using System;
public class IfCloseEnought : MonoBehaviour {
public GameObject[] enemies;
public float range = 10;
public float minimalDistance = 65879;
public float measureDistance;
public GameObject target;
private int number;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
enemies = GameObject.FindGameObjectsWithTag ("Enemy");
foreach (GameObject enemy in enemies) {
measureDistance = Vector3.Distance(gameObject.transform.position, enemy.transform.position);
if(measureDistance < minimalDistance && measureDistance < range){
target = enemy;
minimalDistance = measureDistance;
number++;
}
if(target == null){
minimalDistance = 65879;
}
if(target != null){
if(Vector3.Distance(gameObject.transform.position, target.transform.position) > range){
target = null;
}
}
Array.Clear(enemies, 0, enemies.Length);
number = 0;
Debug.Log(target);
Debug.Log(minimalDistance);
}
}
}
The problem is somewhere in foreach loop (i think). It's executed only on 0th element of array, and doesn't calculate distance between gameObject and elements 1, 2, 3...
It also outputs this error:
NullReferenceException: Object reference not set to an instance of an object IfCloseEnought.Update () (at Assets/Scripts/IfCloseEnought.cs:22)
Where's problem and how to fix it?
Answer by superpig · Jul 30, 2014 at 07:58 AM
Looks like you've got mismatched braces. The foreach loop begins at line 21, but ends at line 40; I think you want it to end between lines 27 and 28 instead.
Thank you for such quick help! Now it works just fine! Thanks!