Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by CharlieFrost · Dec 08, 2019 at 11:04 AM · arraylistdistance check

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!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lgarczyn · Dec 08, 2019 at 01:55 AM 0
Share

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.

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

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.

Comment
Add comment · Show 21 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CharlieFrost · Dec 10, 2019 at 09:58 PM 0
Share

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.

avatar image CharlieFrost · Dec 10, 2019 at 10:16 PM 0
Share

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.

avatar image Larry-Dietz CharlieFrost · Dec 10, 2019 at 10:58 PM 0
Share

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.

avatar image CharlieFrost Larry-Dietz · Dec 10, 2019 at 11:22 PM 0
Share

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.

Show more comments
avatar image lgarczyn · Dec 13, 2019 at 07:16 PM 0
Share

Ah, nice catch. Thanks for the edit.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

137 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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

Preventing Items from shifting in a list 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges