Hi,
I am currently trying to create a dictionary which lists the closest neighbours to a waypoint on my map. The waypoint is defined by an index. Each index is a seperate ‘key’ in the dictionary. The corresponding ‘Values’ are stored as a list of Game Objects.
My code however, seems to be assigning the closest neighbours of the last ‘key’ as the ‘values’ of all keys in the dictionary. This means that each ‘key’ has the same values. Any advice would be much appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TEST : MonoBehaviour
{
int indexes = -1;
Dictionary<int, List<GameObject>> attachedToWaypoint = new Dictionary<int, List<GameObject>>();
List<GameObject> gameObjectForDic = new List<GameObject>();
GameObject[] waypoints;
List<GameObject> newList = new List<GameObject>();
// Use this for initialization
void Start()
{
waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
foreach (GameObject current in waypoints) // Loops through Game objects with tag 'Waypoints"
{
gameObjectForDic.Clear();
indexes += 1;
foreach (GameObject waypointsArroundCurrent in waypoints) // used to compare the distance of neighboring waypoints
{
float distanceSqr = (current.transform.position - waypointsArroundCurrent.transform.position).sqrMagnitude; // Gets distance values
if (distanceSqr < 60) // If waypoints are within a spcific distance
{
gameObjectForDic.Add(waypointsArroundCurrent); //add gameobjects to list
}
}
attachedToWaypoint.Add(indexes, gameObjectForDic); // add 'gameIbjectForDic' list to dictionary as value for specified key which is defined by the 'indexes' variable
}
newList = attachedToWaypoint[10]; // Test the placement of neighbours
foreach (GameObject point in newList)
{
GameObject cubes = GameObject.CreatePrimitive(PrimitiveType.Cube);
cubes.transform.position = point.transform.position;
cubes.transform.GetComponent<Renderer>().material.color = Color.red;
}
}
}