1

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?

Zizo
  • 31
  • 4

1 Answers1

0

So somewhere in the line

 GameObject.Find(tar.spawnedObjects[i].name).GetComponent<PCreator>().Show();

you're getting a NullReferenceException?

This means that at some point, you're attempting to do something with a null object reference as if there were an object there.

Both GameObject.Find and GameObject.GetComponent<T> will return null if the thing being searched for is not found. So either one could be the source of your problem. If I needed to debug this, I would start by breaking up the line into multiple lines:

var obj = GameObject.Find(tar.spawnedObjects[i].name);
var creator = obj.GetComponent<PCreator>();
creator.Show();

Then run it again and see which line the error occurs on.

Also, try putting the whole for loop body inside a try/catch block, and when an error occurs, log a message that includes both the exception's Message property and the current value of i (the for loop index variable) so that you know on which iteration the problem is occurring.

Doing these two things will give you much better data to help you track down the source of your problem.

One other thing. Maybe I'm misunderstanding, as I don't have a huge amount of experience with Unity, but it kind of looks like you're using GameObject.Find to search through the scene graph and find an object with the same name as tar.spawnedObjects[i], which you have just set up in the previous few lines with a unique name. Are you trying to find tar.spawnedObjects[i], which you already have a reference to? If not, what's the intention of this code?

Mason Wheeler
  • 77,748
  • 42
  • 247
  • 453
  • I tried the breakdown you recommended and it's `creator.Show();` that's causing the error. I'm going over the answer you added as duplicate. – Zizo Jan 24 '19 at 23:03
  • 1
    I'm not the one who marked this as a duplicate. What this means is that you have a valid `GameObject` but it doesn't have a `PCreator` component attached. [According to the API reference for Object.Instantiate,](https://docs.unity3d.com/ScriptReference/Object.Instantiate.html) "When you clone a GameObject or Component, all child objects and components will also be cloned with their properties set like those of the original object." So that means that the original object you're cloning (`tar.clonedObject`) doesn't have a `PCreator` on it. That's where you should be looking first. – Mason Wheeler Jan 24 '19 at 23:14
  • For some strange reason it's working now. I deleted the prefab and created it again. – Zizo Jan 25 '19 at 09:30
  • @zizo Oy. That's always annoying, when Unity does weird things like that. I've run into that a few times. Glad I was able to help, though. – Mason Wheeler Jan 25 '19 at 17:26