- Home /
How can I access the variables of arrays with multiple data types?
I've created my own type of array with multiple data types in C#, and then defined it as a public variable:
[System.Serializable]
public class MyType{
private GameObject[] allObjectsTagged;
public string tag;
public Material objectMaterial;
}
public class ArrayTest : MonoBehaviour {
public MyType[] objects;
}
Now I can't work out how I'm supposed to access the variables in my new array. For example, in the start function I would like to use FindGameObjectsWithTag to populate the array "allobjectsTagged" with all the objects tagged by the string variable "tag" above. This way whenever a new element in the "objects" array is assigned, all the objects tagged in this element will be stored in a variable and ready for me to access. But since these are declared in a different class I cannot seam to access them in the start function. Any suggestion how I could do this?
void Start()
{
allObjectsTagged = new GameObject[ArrayTest.$$anonymous$$yType.Length];
for(int i = 0; i < allObjectsTagged.Length; i++)
{
allObjectsTagged[i] = ArrayTest.$$anonymous$$yType[i];
}
}
Is this what you're looking for? You can also use lists. Lists would fit better since they're resizable.
When I do that I get a:
error CS0103: The name `allObjectsTagged' does not exist in the current context
This is my main problem, I can't seam to be able to access the variables from the custom class. I've tried the following but it doesn't work either:
objects[].allObjectsTagged = GameObject.FindGameObjectsWithTag(tag);
Ah, I forgot to tell you that you should also define objects static to be able to reach from another script directly.
public static $$anonymous$$yType[] objects;
Let me know if that works for you.
Thanks for your help Nick4 but I can't actually set the variable as static because I need multiple of these in each scene.
Answer by whydoidoit · Feb 19, 2014 at 03:51 PM
Something like this would do it:
void Start() {
foreach(var o in objects) {
o.allObjectsTagged = GameObject.FindObjectsWithTag(o.tag);
}
}
Hmm I'm still getting the same error though, I can't work out why:
error CS0103: The name `allObjectsTagged' does not exist in the current context
Ah I worked it out, I forget that I needed to make the allObjectsTagged variable a public variable since otherwise it cannot be accessed. After that your solution works. Thanks a lot
Your answer
![](https://koobas.hobune.stream/wayback/20220613134027im_/https://answers.unity.com/themes/thub/images/avi.jpg)