|
Hey everybody, I've been getting hounded by a nullreference error while using array.Length in a C# editor script This is the editor script (With unnecessary script lines removed) And this is the actual script affected: The above posted is what I've narrowed down as the problem, I've been working at it for a while and have had no prevail! To the best of my knowledge, this should be working but it gives this error (ignore line reference): NullReferenceException: Object reference not set to an instance of an object SentryTurretAIEditor.OnInspectorGUI () (at Assets/Editor/SentryTurretAIEditor.cs:14) UnityEditor.InspectorWindow.DrawEditors (Boolean isRepaintEvent, UnityEditor.Editor[] editors, Boolean eyeDropperDirty) UnityEditor.InspectorWindow.OnGUI () System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) Any help would be absolutely amazing! Thanks, -AJ
(comments are locked)
|
|
It seems that your Arrays need to be created, just like any other object. The problem with an array is that you have to specify the length at creation time. You're right, arrays needs to be created and also the contained objects needs to be created, but If you edit the property in the inspector the array AND the contained objects gets created by Unity. If you call
Aug 26 '11 at 12:59 PM
Bunny83
Indeed, if they are in the inspector, even with no elements, you still get an array (with Length==0), not an undefined array.
Aug 26 '11 at 01:11 PM
Waz
Again, sorry for not posting about what I wanted as the output! I' just trying to get the length of the array, and the nullrefernceexception seems to be suggesting that the variable doesn't exist, rather than being equal to 0 or any other int. Thanks for replying though! -AJ
Aug 26 '11 at 01:43 PM
Ariel J
You'd get compile-time errors if any variables didn't exist. Throw in
Aug 26 '11 at 02:52 PM
Owen Reynolds
Wow! Thanks, using if(sentryTurretAI.sentryObjects!=null) did the trick! -AJ
Aug 27 '11 at 12:56 AM
Ariel J
(comments are locked)
|

Well, can't see something wrong. Maybe your target casting cause the problem since you double cast. Keep in mind when using the as-operator when the cast fails it returns null. Are you sure that your sentryTurretAI variable is not null ?
Also you should use only one cast. I do the cast usually in OnEnable and hold the reference in a public variable so i don't need to cast it every inspector update.