- Home /
How Do I Check to See if a Public Variable is Populated using c#?
I have a Public variable in my script that is only used in certain situations. In my script I want to execute c# code if it's empty and other c# code if populated.
I have done web searches about this but all I found were solutions where you looked for a component somewhere else or to check the length equal to 1 using if (someobject.Length == 1) to allow for the transform data according to some that have posted answers.
I tried the latter and got an error GameObject does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?.
I could not find any examples in the Unity documentation for this.
Answer by Bunny83 · Apr 28, 2018 at 04:19 PM
You haven't shown how you declared your variable and what type you actually used. However according to the error you declared a simple GameObject variable and not an array with the element type GameObject. The "Length" property is part of an array type. So i guess you have a variable like this:
public GameObject someobject;
If you want to know if an object was assigned to this variable you have to do
if (someobject != null)
{
// Yeay, we have an object
}
If you want to be able to assign multiple objects you could declare an array of GameObjects like this:
public GameObject[] someobject;
Now "someobject" is actually an array. The array is usually initialized by the inspector to an array with zero elements. However you can change the element count in the inspector to whatever you like. As said above an array has a Length property which tells you the length of the array (the count of elements in the array). Though keep in mind even when the Length is 3, each of those 3 elements could still be null because you haven't assigned any reference to it.
Your question is missing the important information, specifically your actual code. If this doesn't answer your question you should be more specific about your actual problem, what you're trying to do and show your current code.