How do I fill an array of my attached script on a GameObject using C#?
Long version:
If I put the following code into my script the print statement will yield a NullReferenceException. I’m just wondering how to get an array of a script that I have attached to an object. This is very simple with JScript, but, unfortunately, I can’t use JScript for the particular thing that I’m doing.
If I try and protect the print statement with an “if (objEvents != null)” it just so happens that objEvents is always null. If I try and load it without an array, I of course, get the first instance of my script back just fine.
MyScript[] objs = obj.GetComponents(typeof(MyScript)) as MyScript[];
print (objs.Length);
I’ve also tried this with no success.
MyScript[] objs = obj.GetComponents(typeof(MyScript[])) as MyScript[];
print (objs.Length);
I’m an old C++ guy and I’m still learning the quirks of C#, but I may be able to help. I’m not using GetComponents (plural), but here’s how I do something similar using GetComponent:
Since GetComponent returns type Component, you have to cast the return value to the desired type before assigning it to your variable (hence the “(MyScript)” between the function call and the assignment).
So I would think GetComponents would basically be the same as the above, only substitute “MyScript[ ]” for “MyScript” since the return type for GetComponents is an array rather than a single instance. (Though I think you’ll still keep the “typeof” statement the same as above.)