I receive a JSON array from my server onto my unity game client. The array contains different kind of gameobjects, in other words there are different types of objects in one array.
{someArrayOfDifferentObjects:[{name:"bla", element:"ITEM"},{name:"blu",element:"ITEM"},{name:"blu",health:0, element:"ENEMY"}]}
What I try to accomplish is getting the right object type for the target object in a for loop:
private IEnumerator WaitForRequest(WWW www)
{
yield return www;
ResponseObject gameObjects= JsonUtility.FromJson<ResponseObject >(www.text); // from server
object[] base = gameObjects.someArrayOfDifferentObjects;
foreach (object obj in base )
{
ParentObject parent = (ParentObject ) obj;
if (parent.element == "ITEM")
{
Item item = obj as Item; // throws NullReferenceException: Object reference not set to an instance of an object
} else { // other elements}
}
}
{
[Serializable]
public class ParentObject
{
public string element;
}
}
{
[Serializable]
public class Item : ParentObject
{
public string name;
}
}
It tried a couple of things and searched for a solution on the internet, but couldn't find anything that worked with c# in unity. I know this problem can't be too complicated but I'm kind of stuck at the moment.
Can anybode give me a quick hint into the right direction?
greetings,
Codehai