Search Unity

Beginner needing help. Accessing children of arrayed game objects

Discussion in 'Getting Started' started by unity_KLqRzT5ha47IEg, Jul 6, 2019.

  1. unity_KLqRzT5ha47IEg

    unity_KLqRzT5ha47IEg

    Joined:
    Jun 3, 2019
    Posts:
    1
    In my first ever project, I have a series of game objects called "Job" and each one has a child object named "Task". I want to call a method in the script attached to "Task" which receives a Boolean to toggle whether or not the player can complete the task. This is what that method looks like on the task.

    public void IsActiveTask(bool active)
    {
    gameObject.SetActive(active);
    }
    }

    I have a gamecontroller object that's responsible for setting one task out of the array as active. My declarations look like this:

    public int numOfJobs = 3;
    public int numOfCoworkers = 3;
    public GameObject[] jobsArr;
    public GameObject[] coworkersArr;
    bool isWorking = false;

    It's possible I haven't set the array correctly, but I've been able to drag the associated objects into the inspector boxes.

    I'm trying to disable the child object on start up, but I'm not sure how to do that in the array form.
    TL;DR How do I run a method on the child of an object stored in an array?
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Please use code tags when posting code.

    As for your question, the easiest way is to change the type of those arrays from GameObject to whatever script you expect those objects to have (i.e., whatever script you want to call a method on). Then you can just zip through them and call the method:

    Code (CSharp):
    1. foreach (var item in jobsArr) {
    2.     item.DoSomething();
    3. }