How do I use GetComponent to populate and array?
I have a class which uses Monobehaviour and I would like to store it in an array. I know what I could use a list instead, but I was wondering how this code works for arrays.
Firstly I have created a test class to place in the array:
public class TestObject : MonoBehaviour {
int number = 0;
public int GetNumber() {
return number;
}
public void Initalize() {
number += 1;
}
public void InitalizeWithParameter(int passedNumber) {
number = passedNumber;
}
}
If it wasn't for the monobehaviour this code below is how I would declare and initialise the array (I am initialising it with a method rather than a constructor in this example):
TestObject[] two = new TestObject[10];
for (int i = 0; i < 10; i++) {
two.Initialize();
Debug.Log(two[i].GetNumber() + 20);
}
Because the class uses of MonoBehaviour I am unable to use the 'New' keyword. Online everybody recommends using 'GetComponent' instead. I have tried the example below, but the syntax is incorrect. Does anybody know what this should look like, or another way of getting this working? I have really tried, but need some help at this stage.
TestObject[] three = GetComponent<TestObject>()[10];
for (int i = 0; i < 10; i++) {
three.Initialize();
Debug.Log(three[i].GetNumber() + 20);
}
Answer by yanivng · Sep 10, 2017 at 07:45 PM
GetComponent doesn't create any new objects. You might want to start here: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
You can put your MonoBehavior script on a prefab and instantiate from that prefab.