- Home /
Answered by robertbu
Why does this return a NullReferenceException?
I am creating a procedural item placement script and editor. The editor allows for adding custom "SceneryObjects" and setting their properties in the inspector. There is also an option to delete the SceneryObject with an "X" button. However, upon clicking the "X" button on an SceneryObject without a GameObject assigned to it, I get a NullReferenceException. After assigning any GameObject to the SceneryObject and clicking the "X" button again, the SceneryObject is deleted. Why is the "X" button not working for SceneryObjects without GameObjects set to them?
SceneryObject.cs :
using UnityEngine;
using System.Collections;
[System.Serializable]
public class SceneryObject{
public string name;
[Range(0.0f, 1.0f)]
public float spawnProbability;
public float minHeight;
public float maxHeight;
[Range(0.0f, 90.0f)]
public float minSteepness;
[Range(0.0f, 90.0f)]
public float maxSteepness;
public bool randRotX = true;
public bool randRotY = true;
public bool randRotZ = true;
public GameObject obj;
public bool makeStatic = true;
public Vector3 minScale;
public Vector3 maxScale;
}
TestItemPlacement.cs :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[ExecuteInEditMode]
public class NewItemPlacement : MonoBehaviour {
public Terrain terr;
public Transform cloneParent;
public List<SceneryObject> objs = new List<SceneryObject>();
public void checkAndPlace(Terrain terr, SceneryObject sO, int aMPX, int aMPY, Vector2 aMPos, Transform par)
{
//Generation code
}
public void ScanAndPlace(Terrain terr, SceneryObject so)
{
//More code
}
public void ClearAll(string nam, Transform par)
{
//And more code
}
}
TestPlacementEditor.cs :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(NewItemPlacement))]
public class ItemPlacementEditor : Editor {
NewItemPlacement myScript;
void OnEnable()
{
myScript = (NewItemPlacement)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if(GUILayout.Button ("Add"))
{
myScript.objs.Add(new SceneryObject());
}
for(int i = 0; i < myScript.objs.Count; i ++)
{
GUILayout.BeginHorizontal ();
if(GUILayout.Button ("Generate " + i))
{
myScript.ScanAndPlace(myScript.terr, myScript.objs[i]);
}
if(GUILayout.Button ("Delete " + i))
{
myScript.ClearAll (myScript.objs[i].obj.name, myScript.cloneParent);
}
if(GUILayout.Button ("X", GUILayout.Width (20)))
{
myScript.ClearAll(myScript.objs[i].obj.name, myScript.cloneParent);
myScript.objs.RemoveAt (i);
}
GUILayout.EndHorizontal();
}
}
}
Please post a copy of the error message from the console. Note I don't think TestPlacementEditor.cs will compile. 'target' is not declared anywhere.
Figured it out because of you! Thanks! I should have read the entire error message! Thanks!
You're calling obj.name in your ClearAll method, so it's throwing a null reference if obj (Your GameObject) isn't set.