Search Unity

Resolved How can I use GetComponent for multiple game objects in one line of code?

Discussion in 'Scripting' started by tabagoo, Nov 11, 2020.

  1. tabagoo

    tabagoo

    Joined:
    Oct 8, 2020
    Posts:
    4
    For context, I have a team of AI bots who all have a bool called "inJail" that I want to set to false whenever one bot breaks out the rest of them. Basically, I need a line of code so one bot can access the scripts of all the other bots so it can change "inJail" for all the AI all at the same time. This might sound lazy but I found it too tedious to reference every single bot in each other's script. I hope there's shorter/more efficient way of doing so?? I tried using "publicGameObject[ ] bots" but it doesn't offer a GetComponent method.
     
  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    Using an array like you tried is a good approach. You will need to iterate over the array and access each bot individually.

    Something like:

    Code (CSharp):
    1. foreach(var bot in bots) bot.GetComponent<AI>().inJail= false;
     
    tabagoo and Vryken like this.