- Home /
Question by
elsharkawey · Jun 20, 2018 at 10:47 PM ·
c#gameobjectfindname
GameObject.Find can't find the object after i changed her name
I created this script to create a group of plane meshes with offset between them in my game scene
then change there names and give id for every one of them
creatingobjectslist script
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;
}
}
void Update () {
}
}
then I created this script and attached it to another object to move my object to one of the objects that 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 runnig that I get this error
NullReferenceException: Object reference not set to an instance of an object
Comment
Best Answer
Answer by sgthale · Jun 20, 2018 at 11:02 PM
You are changing the TargetPrefab's name not the one you instantiated. Look:
TargetPrefab.name = "Ben" +i;
you want something like:
instantiatedPrefab.name = "Ben" +i;