- Home /
How do I get unity to tell me what type of variable a variable is?
I need to know how to tell the type of variable a variable is through a script. I am reciving some data from a JSON file and parsing through it. I get back a bunch of variables based on an attribute I choose, but some atrributes return floats and some return ints. I have overloading some functions in order to handle either type but I would like to know how to find the type of variable so I know what kind of arrays to create and fill with the variables. Any ideas?
It sounds like you need to analyze the data that's co$$anonymous$$g in, then define it based on the string you're getting.
$$anonymous$$y first thought for ints and floats would be to treat it as a string on import. Then do a quick search in the string - if it has a period, convert to float. If no period, convert to int. If it has letters, convert to string.
Granted, there may be times you want to define something that looks like an int as a float, but that's another matter.
How do I do a search? I have trying using the IndexOf method after converting a variable from the dataset into a string but it says there is no method called IndexOf.
Are you only dealing with ints and floats? If so, my thoughts would be something like this:
function defineType(value : String){
if("." in value){
Debug.Log("Value is a float")
}
else{
Debug.Log("Value is an integer")
}
That said, this will cause issues if you call it for anything but numbers. Do you need to be able to do that, too?
Answer by alexfeature · Jan 07, 2013 at 08:06 PM
Using separators to deduce numeric types is not a good idea. This approach will fail when you get data from a server set up with different regional settings than the client analysing data. So, you would need to check for two symbols ',' and '.' to be sure.
This will introduce unnecessary overhead while processing imported data.
I would recommend using Float.TryParse() first. All numeric values that pass this cast should be treated as floats. If you have other data types such as DateTime you can .TryParse() them too. Any variables failing these casts can be assumed to be Strings.
This is not ideal but unless we are talking about massive amounts of calculations per frame you can ignore ints all together.
Perhaps if you could share a bit more details on what exactly you are receiving a better approach can be found.
EDIT : Forgot the code sample :D
// In your import function loop
foreach (var value in myJSONValues)
{
var myFloat = 0F;
var myDate = (DateTime?)null;
if(float.TryParse(value, out myFloat))
{
// myFloat now has a value and you can add it to your Floats array
continue;
}
if(DateTime.TryParse(value, out myDate))
{
// myDate now has a value and you can add it to your Dates array
continue;
}
// All casts failed you can treat value as string...which it is anyways :D
// Add value to Strings array
}
Regards, Alex