I keep getting the error NullReferenceException: Object reference not set to an instance of an object
when trying to access a method from an attached script.
My editor code below creates prefab copies in a circle. I placed a prefab for the clonedObject
CircleSpawn
public class CircleSpawn : MonoBehaviour
{
public float radius, radiusLast, spin, spinLast;
public int numOfItems;
//public int oldNumOfItems = 0;
public GameObject clonedObject;
public List<GameObject> spawnedObjects;
}
CircleSpawnEditor
[CustomEditor(typeof(CircleSpawn))]
public class CircleSpawnEditor : Editor
{
public override void OnInspectorGUI()
{
var tar = (CircleSpawn)target;
tar.clonedObject = (GameObject)EditorGUILayout.ObjectField(tar.clonedObject,
typeof(GameObject), true);
if (!tar.clonedObject) return;
EditorGUILayout.LabelField("Radius"); // Set as required
tar.radius = EditorGUILayout.Slider(tar.radius, 0f, 5f);
EditorGUILayout.LabelField("Angle"); // Set as required
tar.spin = EditorGUILayout.Slider(tar.spin, 0f, 360f);
EditorGUILayout.LabelField("Number of Items"); // Set as required
tar.numOfItems = EditorGUILayout.IntSlider(tar.numOfItems, 0, 12);
EditorGUILayout.LabelField("Object");
float angle, angleBetween = 360.0f / tar.numOfItems;
if (tar.spawnedObjects == null)
tar.spawnedObjects = new List<GameObject>();
if (tar.spawnedObjects.Count != tar.numOfItems)
{
foreach (var ob in tar.spawnedObjects)
DestroyImmediate(ob);
tar.spawnedObjects.Clear();
angle = 0f;
for (int i = 0; i < tar.numOfItems; i++)
{
var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
var localPos = rot * Vector3.right * tar.radius;
tar.spawnedObjects.Add(Instantiate(tar.clonedObject,
tar.transform.position + localPos, rot));
angle += angleBetween;
tar.spawnedObjects[i].name = tar.spawnedObjects[i].name + (i + 1);
var obj = GameObject.Find(tar.spawnedObjects[i].name);
var pCreator = obj.GetComponent<PathCreator>();
pCreator.DrawBezierCurve();
GameObject.Find(tar.spawnedObjects[i].name).GetComponent<PCreator>().Show();
}
}
if (!Mathf.Approximately(tar.spin, tar.spinLast) ||
!Mathf.Approximately(tar.radius, tar.radiusLast))
{
tar.spinLast = tar.spin;
tar.radiusLast = tar.radius;
angle = 0f;
for (int i = 0; i < tar.numOfItems; i++)
{
var rot = Quaternion.Euler(0f, 0f, tar.spin + angle);
var localPos = rot * Vector3.right * tar.radius;
tar.spawnedObjects[i].transform.position =
tar.transform.position + localPos;
tar.spawnedObjects[i].transform.rotation = rot;
angle += angleBetween;
}
}
}
}
The error occurs at the line
GameObject.Find(tar.spawnedObjects[i].name).GetComponent<PCreator>().Show();
How can I solve this issue?