So I don´t know if I´m missing an dumb error of myself but my problem is:
I´ve got an class which deserializes a json file into a tree-structure. That part is working without an error. Now while doing this i want to create Objects of another class - we just call it “CityObject” for the moment.
public class CityObject : MonoBehaviour {
private GameObject gameObject;
public ArrayList children;
public int width;
public CityObject(GameObject prefab, int newWidth)
{
gameObject = Instantiate(prefab);
children = new ArrayList();
width = newWidth;
}
}
Depending on the Information in the json file, the GameObject should get a simple cube prefab or a flat cube prefab and instantiate it. So far so good - in the unity Scene all Objects are created, so in my example there are 5 created GameObjects - 2 flat and 3 simple cubes.
public class CityBuilder : MonoBehaviour {
public GameObject plane;
public GameObject cube;
public CityObject origin;
private int maxW = 0;
private ProjectView ProcessProjectData(string jsonString)
{
ProjectView parsejson = JsonUtility.FromJson<ProjectView>(jsonString);
return parsejson;
}
private GameObject FindPrefab(string type)
{
switch (type.ToLower())
{
case "block": newPlane = false; return cube;
case "scope": newPlane = true; return plane;
default: return null;
}
}
private CityObject CreateGameObjectFromProjectData(ProjectData projectData, CityObject cityObjectParent)
{
var prefab = FindPrefab(projectData.type);
if (!prefab)
return null;
CityObject rootCityObject = new CityObject(prefab, getSubtreeWidth(projectData));
if(maxW == 0)
{
maxW = rootCityObject.width;
}
scaleObject(rootCityObject);
/* * *
* If an object has one or more children, then the children should execute this method on their own.
*/
if (projectData.children != null)
{
foreach (ProjectData data in projectData.children)
{
Debug.Log(data.id);
}
foreach (ProjectData data in projectData.children)
{
CityObject newChild = CreateGameObjectFromProjectData(data, rootCityObject);
rootCityObject.appendChild(newChild);
}
}
return rootCityObject;
}
The problem is that in line 40 i want to scale the gameObject of the cityObject like this:
private void scaleObject(CityObject node)
{
float scaleRatio = (float)(node.width/maxW);
node.gameObject.transform.localScale.Set(scaleRatio, scaleRatio, scaleRatio);
}
Then there is a NullReference Error for the node.GameObject - so there seems to be no reference between the cityObject and the GameObject. This is the part i can´t understand. Is it the Instantiate in the CityObejct Constructor? Isn´t the Instantiate creating a Reference between the “Script-Object” and the Gameobject in the unity-Scence?