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