- Home /
Trying to put items in an updating list into an array.
Hi, this is my first post so sorry if it is not formatted very well. I have food prefabs spawning randomly. When these prefabs are spawned they are added into a list:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class FoodSpawner : MonoBehaviour
{
// Variables
// Spawn rate
private float foodSpawnRate = 2f;
// Time until next spawn
private float nextFoodSpawn = 1f;
// The maximum amount of Food
private float maxFood = 30f;
// Food prefab I want to spawn
public GameObject Food;
// Create a list of all the "Food"s
public List<GameObject> Foods = new List<GameObject>();
void Update()
{
// If it is time to spawn Food
if (ShouldSpawnFood() && Foods.Count < maxFood)
{
SpawnFood();
}
}
// This method returns if time has surpassed the next Food spawn
private bool ShouldSpawnFood()
{
return Time.time > nextFoodSpawn;
}
// This function spawns the Food
private void SpawnFood()
{
// Instantiate the Food
// Call it 'thisFood' upon instantiation
GameObject thisFood = Instantiate(Food, new Vector3(Random.Range(-4, 4), transform.position.y, Random.Range(-4, 4)), transform.rotation);
// If the Food that has just been instantiated is not already in the list then add it
if (!Foods.Contains(thisFood))
Foods.Add(thisFood);
// Reset the nextFoodSpawn to the foodSpawnRate
nextFoodSpawn = Time.time + foodSpawnRate;
}
}
I want my animal to get the position of the nearest food and walk towards it (to eat it). I initially tried to achieve this using the list but to no avail. Looking at forums/videos, it seems to be the norm to use arrays to search through the foods. So I am attempting to turn this list into an array:
public class Herbivores : MonoBehaviour, Animals
{
//variables
public float size;
public float speed = 5f;
public float hunger;
public float age;
public float ageRate;
// Declare arrayFoods array
public GameObject[] arrayFoods = new GameObject[30];
// Allows us to access the Foods list
FoodSpawner FoodSpawnerScript;
//Transform GetClosestFood(List<Transform> Foods, Transform fromThis)
//{
// Transform bestTarget = null;
// float closestDistanceSqr = Mathf.Infinity;
// Vector3 currentPosition = fromThis.position;
// foreach (Transform potentialTarget in Foods)
// {
// Vector3 directionToTarget = potentialTarget.position - currentPosition;
// float dSqrToTarget = directionToTarget.sqrMagnitude;
// if (dSqrToTarget < closestDistanceSqr)
// {
// closestDistanceSqr = dSqrToTarget;
// bestTarget = potentialTarget;
// }
// }
// return bestTarget;
//}
void Start()
{
// Access the FoodSpawner script
FoodSpawnerScript = GetComponent<FoodSpawner>();
// The agent's age begins at 0 for obvious reasons
age = 0;
}
void Update()
{
// Increase the agent's age over time
age += (ageRate * Time.deltaTime);
FindFood();
}
public void FindFood()
{
// Variables used for finding closest food
float distToClosestFood = Mathf.Infinity;
GameObject closestFood = null;
// Firstly, convert the Foods list to an array called 'arrayFoods'
// This enables us to still keep a growing list (and a maxFood count), whilst easily searching through to find the nearest Food
FoodSpawnerScript.Foods.AddRange(arrayFoods);
// Go through each Food item in the arrayFoods array
foreach (GameObject Food in arrayFoods)
{
// Work out the distance from each Food item to the animal
float distToFood = (Food.transform.position - this.transform.position).sqrMagnitude;
// If the distance is smaller than the distance to the current closest Food
if (distToFood < distToClosestFood)
{
// Overwite the closest Food item
distToClosestFood = distToFood;
// Set the closestFood GameObject to this Food
closestFood = Food;
}
}
// Draw a line to the nearest Food
Debug.DrawLine(this.transform.position, closestFood.transform.position);
}
I thought my declaring the array at the beginning of the script, then using
FoodSpawnerScript.Foods.AddRange(arrayFoods);
I would have success, but no :(. As you can see I have commented out a method that did not work out for me (to be honest I simply did not know how to use the returned value to walk towards). Please keep answers as simple as possible as I am fairly new, cheers!
A list will work just as well as an array to iterate. Just use something like foreach (var food in foodList)
.
However if you want help, you need to actually state what is not working. You also need to show that you went through the debugging process, by using Debug.Log or similar to see how your code currently behaves.
For example, maybe your food list is empty. $$anonymous$$aybe something else is going wrong. You need to check.
Answer by Larry-Dietz · Dec 08, 2019 at 04:12 PM
As ceandros commented, you should be able to do whatever you want with the list, pretty similar to the way you would do it with an array. That being said, if you want an array, this should help you.
Generic lists have a method called ToArray()
so you could do this, to create your array from the list...
GameObject[] FoodArray = Foods.ToArray();
That would create an array named FoodArray, and populate it with all the items in your Foods list.
Hope this helps, -Larry
Edit to show what his ultimate problem was, and how it was corrected.
His routine that found the closest food was storing that food in a local variable, named the same as the global variable. It was returning the food, but the calling function was not doing anything with the returned value. It was fixed by making the following change...
public void FindFood()
{
ChooseNearestFood();
}
was changed to
public void FindFood()
{
closestFood = ChooseNearestFood();
}
This assigned the food that was found to the global closestFood so the rest of the routine had access to the value.
Thanks for the response. I believe I am extremely close however I can't seem to wrap my head around how to get this code working and so any more help would be much appreciated. Here is the code I am using to find the closest Food GameObject: GameObject ChooseNearestFood() { // Variables used for finding closest food float distToClosestFood = $$anonymous$$athf.Infinity; GameObject closestFood = null;
// Go through each Food item in the arrayFoods array
foreach (GameObject Food in Foods)
{
// Work out the distance from each Food item to the animal
float distToFood = (Food.transform.position - this.transform.position).sqr$$anonymous$$agnitude;
// If the distance is smaller than the distance to the current closest Food
if (distToFood < distToClosestFood)
{
// Overwite the closest Food item
distToClosestFood = distToFood;
// Set the closestFood GameObject to this Food
closestFood = Food;
}
}
return closestFood;
}
This appears to be the standard way. I want to use my update function to call my 'FindFood' and '$$anonymous$$ove' functions:
void Update()
{
// Increase the agent's age over time
age += (ageRate * Time.deltaTime);
FindFood();
$$anonymous$$ove();
}
public void FindFood()
{
ChooseNearestFood();
}
public void $$anonymous$$ove()
{
}
However, my issue is that no matter how I try to use my found object 'closestFood', Unity complains the 'Object reference is not set to an instance of an object', which I suppose makes sense, as 'ChooseNearestFood' is called during runtime. Thanks in advance.
I suppose what I am saying now is, I am not sure how to use a returned GameObject since it's reference is not set and it is spawning at any time. Thanks.
Have you confirmed that closestFood is being populated with a GameObject, or if it is still null?
As long as this script is part of your FoodSpawner, it should have access to the Foods array. If it is not, change your loop to use a reference to the FoodSpawner, so it has an array of gameobjects to loop through.
As long as it is actually accessing an array of gameobjects in the scene, then you code looks good.
I believe you just hit the nail on head. It must be null. I thought using 'foreach (GameObject Food in Foods)' and 'closestFood = Food' was enough, because each gameobject spawned is called 'Food'. Sorry to be a pain but what would be the code to reference to my Food Spawner GameObject in the loop? Thanks again.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Can't Activate a GameObject from Array 1 Answer
Make the audio manager select from an array of sounds 1 Answer
List all children in array? 5 Answers