I want to populate an array so that each element has 2 fields in the inspector, a string and a bool.
I have 5 objects with the tag “TouchZone” in the scene.
I want to populate the array using GameObject.FindGameObjectsWithTag(“TouchZone”)
I have the following:
[System.Serializable]
public class Data
{
public string objectName;
public bool objectBool;
}
public Data[] dataArray;
I know I need a for loop, I just don’t understand how to add to the array or how to write the for loop properly to add the data to the array properly.
int x = GameObject.FindGameObjectsWithTag("TouchZone").Length;
for (int i = 0; i < x; i++)//Get the list length of Scenes
{
//What do I add here?
}
I figure I need to add it to the for loop above but I dont know the proper code to add the data into the case array
You should rethink your approach. First of all an array can not change its size. The size of an array need to be specified when the array is created. Second it wasn’t really clear what exact data you want to store in that string and boolean value. If it’s the name of the objects you found through the FindGameObjectsWithTag method it would make more sense to store the actual references to those objects in your class. Specifically something like that:
[System.Serializable]
public class Data
{
public GameObject obj;
public bool objectBool;
}
public Data[] dataArray;
// [ ... ]
var objs = GameObject.FindGameObjectsWithTag("TouchZone");
// create new Data array with the same number of elements as we have in the objs array.
dataArray = new Data[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
// create new Data object
var tmp = new Data();
// set the values you want.
tmp.obj = objs*;*
tmp.objectBool = false;
// store the Data object in our dataArray dataArray = tmp; } If, for some reason you really want to store a copy of the names of the objects, instead of storing the reference to the object in the class you just store the name (or whatever you want from those object). So if the Data object looks like your original one, you would do something like tmp.objectName = objs*.Name;*
My full code for just this example that is working thanks to @Bunny83 is this (for those that were interested):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class boolArray : MonoBehaviour
{
//public bool[] touchZonesToggle;
[System.Serializable]
public class Data
{
public GameObject obj;
public bool objectBool;
}
public Data[] dataArray;
void Start()
{
// [ ... ]
var objs = GameObject.FindGameObjectsWithTag("TouchZone");
// create new Data array with the same number of elements as we have in the objs array.
dataArray = new Data[objs.Length];
for (int i = 0; i < objs.Length; i++)
{
// create new Data object
var tmp = new Data();
// set the values you want.
tmp.obj = objs*;*
tmp.objectBool = false;
// store the Data object in our dataArray dataArray = tmp; }