Search Unity

Is there a way to assign a int number to a gameobject array?

Discussion in 'Scripting' started by getmyisland_dev, Aug 15, 2021.

  1. getmyisland_dev

    getmyisland_dev

    Joined:
    Dec 22, 2020
    Posts:
    100
    I want to assign an int to an array of gameobjects like the title says.

    It should look something like this:
    Code (CSharp):
    1. int currentCamera;
    2.  
    3. currentCamera = cameras[]
    4.  
    I want that, because if I run a void I want to check if a specific camera is active, like that:
    Code (CSharp):
    1. if(currentCamera == 5)
    and then do something.

    I could do it with a lot of bools, but this would be so messy that it's way smarter to do it like this.

    Thanks in advance Max.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    That's not a thing.

    Check some tutorials or examples on arrays and how to access elements within them.

    Accessing elements of an array can be called:

    - accessing elements of array
    - indexing the array
    - dereferencing
    - looking up
     
  3. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Wrap your relevant data in a class or struct:
    Code (CSharp):
    1. public class ActiveCamera
    2. {
    3.   public Camera camera;
    4.   public bool isActive;
    5. }
    Then create an array of that wrapper:
    Code (CSharp):
    1. ActiveCamera[] cams = //etc...
    Then filter the array to get the relevant object you're looking for:
    Code (CSharp):
    1. Camera current = GetCurrentCamera();
    2.  
    3. //...
    4.  
    5. Camera GetCurrentCamera()
    6. {
    7.   Camera current = null;
    8.  
    9.   for(int i = 0; i < cams.Length; i++)
    10.   {
    11.     if(cams[i].isActive)
    12.     {
    13.       current = cams[i].camera;
    14.       break;
    15.     }
    16.   }
    17.  
    18.   return current;
    19. }