0
\$\begingroup\$

I created this script to create a group of plane meshes with offset between them in my game scene, then change their names and give an ID to every one of them:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class creatingobjectslist : MonoBehaviour {

    public GameObject TargetPrefab;

    void Start () {
        for (int i = 0; i < 5; i++){
            Instantiate(TargetPrefab, new Vector3(i * 1.5f, 0f, 0f), Quaternion.identity);
            TargetPrefab.name = "Ben" +i;
        }
    }
}

Then I created this script and attached it to another object to move my object to one of the objects that was created with the creatingobjectslist script

using UnityEngine;
using System.Collections;
public class MoveCubeTogrid : MonoBehaviour {
    UnityEngine.AI.NavMeshAgent agent;

    void Start () {
        agent = GetComponent< UnityEngine.AI.NavMeshAgent >();
    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
                    //agent.destination = hit.point;
                    agent.destination = GameObject.Find("Ben0").transform.position;
            }
        }
    }
}

and after running that I get this error

NullReferenceException: Object reference not set to an instance of an object
\$\endgroup\$
1

1 Answer 1

2
\$\begingroup\$

You're renaming the prefab, not the clone:

TargetPrefab.name = "Ben" +i;

As such, the first one has OriginalName (clone) for a name, the second one is called Ben0 (clone), then Ben1 (clone) and so on.

If you had checked your scene hierarchy at runtime you would have noticed this.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .