Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Getting the individual scripts of gameobjects within an array?

Discussion in 'Scripting' started by Lethn, Apr 26, 2019.

  1. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    I've been getting used to arrays and experimenting with them a bit and I plan on messing around with lists properly as well and I was wondering if is possible to get the scripts of gameobjects within an array.

    By this I mean what I've got planned for a script I'm making is that I'm going to be getting NavMesh Agents and putting them into an array. I want to then get the script attached to these navmesh agents within the array and then move them to a certain point. Am I right in thinking that in order to do that I would need to get the script component of each navmesh agent and then execute the function required to move them?

    The closest answer to this I've found so far is here.

    https://answers.unity.com/questions/1155911/how-to-get-an-array-of-gameobjects-that-have-a-cer.html

    Not entirely sure whether this is the correct answer though for my specific problem.
     
  2. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,599
    The code in the original post or the second post would probably be ok if you only need to access these components every once-in-a-while. If you access them frequently, then you'd want to find them once and store them all in a collection, I would think.
     
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    In general, if you already have a GameObject, and you want to get a specific script that you know is attached to that object, you should use

    object.GetComponent<ScriptType>()
     
    SAMYTHEBIGJUICY likes this.
  4. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Unfortunately I need to get gameobjects that are instantiated, I have them added into the array as they are instantiated into the game.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class VillagerCount : MonoBehaviour
    6.  
    7. {
    8.     public GameObject[] TotalVillagersArray;
    9.  
    10.     private void Update()
    11.  
    12.     {
    13.         int VillagerPopulation = transform.childCount;
    14.  
    15.         TotalVillagersArray = GameObject.FindGameObjectsWithTag("Villager");
    16.     }
    17.  
    18. }
    19.  
    It's actually quite simple the code itself I've used to get the gameobjects but I'm just unsure of how to get all of the ones in the array oh and I just thought of something I could try, I could use the tag couldn't I and get the scripts from there.
     
  5. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    What do you mean "get" the ones in the array? You already have the ones in the array; they're in the array. If you want to do something to each thing in the array, you can say
    Code (CSharp):
    1. foreach (var thing in MyArray)
    2. {
    3.     // Do stuff with thing
    4. }
     
    Ed-Gilmour likes this.
  6. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Sorry lol I wasn't being very clear, and for crying out loud of course there's an exact command for doing what I want I didn't know about what I meant was I wanted to get the script for each individual gameobject within the array rather than just blanket grab the script from a prefab etc.

    I'll try your method and see if it works, thanks, looks like it's exactly what I need.
     
  7. supermoof

    supermoof

    Joined:
    Sep 24, 2015
    Posts:
    48
    Correct me if I'm wrong but I'm assuming you want to get access an array of gameobjects and then make another array of a component from those gameobjects? (example: navmeshagent). Something like this?

    Code (CSharp):
    1.     GameObject[] objectArray;
    2.     List<NavMeshAgent> agents;
    3.  
    4.         foreach (var item in objectArray)
    5.         {
    6.             if(item.GetComponent<NavMeshAgent>())
    7.             {
    8.                 NavMeshAgent agent = item.GetComponent<NavMeshAgent>();
    9.                 agents.Add(agent);
    10.             }
    11.         }
     
  8. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    I didn't want to add an agent but I wanted to move them and use set destination etc.
     
  9. supermoof

    supermoof

    Joined:
    Sep 24, 2015
    Posts:
    48
    The code that I posted will create a list of NavMeshAgents from the the object array. After this list is created, you can then iterate through the agent list to do what you want with them.

    Code (CSharp):
    1. foreach (var item in agents)
    2.         {
    3.             item.SetDestination(Vector3.zero);
    4.         }
     
  10. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    What is the item variable supposed to be? Is it the gameobject within the array?

    Yeah I think I'm completely misunderstanding what it's for lol.
     
  11. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,599
    Are you not familiar with the foreach loop in C#? In this case, it will loop through all of the items in agents one-at-a-time, and for each iteration it will set "item" to whichever item is currently on.

    It would be like:
    Code (CSharp):
    1. var item;
    2. for (int i=0;i<agents.Length;i++)
    3. {item = agents[i];
    4.  item.SetDestination(Vector3.zero);
    5. }
     
  12. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    I've just realised I've actually been a moron and over complicated this far too much and I think @Antistone 's solution was the correct one, I've just had a severe case of making things complicated for no bloody reason. He was right, and for whatever reason I kept on thinking I needed an array when actually it would be simpler to just do it directly from the gameobjects that were needed.

    I'm not terribly familiar with foreach loops as I haven't needed to use them very much, what I will do though is I'm going to look up some faction systems in unity and how they work because I think that's what I need to get everything working.
     
  13. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Sorry everyone lol I should probably explain what I'm trying to do and I'll do a quick bullet point list to keep things simple.

    . I have a bunch of navmesh agents that are children of an overall empty gameobject

    . The empty gameobject counts the number of gameobjects created and destroyed in other words it acts like a population counter

    . When a different gameobject is moved I want that gameobject to have a percentage which sends a certain number of navmesh agents to a position in the game world however I'm trying to make sure that it's only the navmesh agents that are the children of the gameobject empty that I mentioned that move as opposed to any others

    My head actually hurts, but I will finish this if it kills me >_<

    Edit: OH! I know how to solve this problem, is it possible to check a variable of a parent that a child is attached to?
     
  14. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
  15. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Okay guys I got everything working in a basic way for now, I'll post up the code if your curious as to what the hell I've been going on about.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class VillagerWanderScript : MonoBehaviour
    7.  
    8. {
    9.     public float wanderRadius;
    10.     public float wanderTimer;
    11.     private float timer;
    12.     public Transform worshipSite;
    13.  
    14.     private Transform target;
    15.     public NavMeshAgent agent;
    16.     DragTotemScript dragTotemScript;
    17.  
    18.     void OnEnable()
    19.  
    20.     {
    21.         agent = GetComponent<NavMeshAgent>();
    22.         timer = wanderTimer;
    23.     }
    24.  
    25.     void Update()
    26.  
    27.     {
    28.         VillagerWander();
    29.  
    30.         if (GameObject.Find("VillageCentreTotem").GetComponent<DragTotemScript>().totemDragAmount == 9.229977f)
    31.  
    32.         {
    33.             GoToWorshipSite();
    34.         }
    35.  
    36.     }
    37.  
    38.     public static Vector3 RandomnavSphere(Vector3 origin, float distance, int layermask)
    39.  
    40.     {
    41.         Vector3 randomDirection = Random.insideUnitSphere * distance;
    42.         randomDirection += origin;
    43.  
    44.         NavMeshHit navHit;
    45.  
    46.         NavMesh.SamplePosition(randomDirection, out navHit, distance, layermask);
    47.  
    48.         return navHit.position;
    49.  
    50.     }
    51.  
    52.     public void VillagerWander ()
    53.  
    54.     {
    55.         timer += Time.deltaTime;
    56.  
    57.         if (timer >= wanderTimer)
    58.  
    59.         {
    60.             Vector3 newPosition = RandomnavSphere(transform.position, wanderRadius, -1);
    61.             agent.SetDestination(newPosition);
    62.             timer = 0;
    63.  
    64.         }
    65.     }
    66.  
    67.     public void GetSleep()
    68.  
    69.     {
    70.         GameObject maleStatsEmpty = GameObject.Find("MaleStatsEmpty");
    71.         maleStatsEmpty.GetComponent<VillagerStatsMale>();
    72.     }
    73.  
    74.     public void GoToWorshipSite()
    75.  
    76.     {
    77.         agent.SetDestination(worshipSite.transform.position);
    78.     }
    79.  
    80. }
    81.  
    As an extra note, I hadn't realised that GameObject.Find in the latest versions of unity only searches for children so I ended up just using that and it's all working fine now, I just need to work out percentage maths with floats and then everything will be good to go.

    I might be able to simply get the count of the children within my gameobject empty rather than rely on arrays and use that to calculate how many navmesh agents need to move.
     
  16. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
  17. SAMYTHEBIGJUICY

    SAMYTHEBIGJUICY

    Joined:
    Jul 12, 2023
    Posts:
    44
    Sorry for resurrecting but I was looking for answers to my idiotically insane issue of not getting unique values from the same script for multiple game objects for ages and want to add that I replaced all my findobjectbyanytype with this advice by Antistone - seems obvious now

    Just want to say thank you for all your answers and for bestowing us mortals with the tomes of your unity genius.