Hello, I am new to Unity engine and face a problem in my work…
Sorry for the stupid question and Thanks for your time to read it.
I have a button , by clicking the button I will instantiate a prefab with 4 child gameobject.
I have to set different value of 4 child gameobject each time…
But when I use GameObject.Find() function to set the value when I instantiate, it changes all of the child gameobject’s value, because of all prefabs’ child gameobject name are same…
I can’t figure the solution out, for now.
What should I do? Using a different function or there are some ideas to change the value of child gameobject which is recently instantiated?
The “Instantiate” function returns a reference to the object that was created. Just store that reference into a variable and make any change you want:
using UnityEngine;
public class Test() {
GameObject prefab;
void Start() {
GameObject clone = (GameObject)Instantiate(prefab);
clone.name = "I'm a clone of the prefab".
Debug.Log(clone.name);
GameObject clone2 = (GameObject)Instantiate(prefab);
clone2.name = "I'm a different clone".
Debug.Log(clone2.name);
}
}
Storing the reference after the instantiation of the prefab and iterating over the childs like shown in that link you should be able to change any value of each child.
Generally speaking it is bad practice to use GameObject.Find() because it kills frame rate if used frequently. The better practice is to maintain a reference to the GameObject. I believe, in your case (correct me if I am wrong) you have one prefab and that prefab has four children, and you want to modify some values in the children. (I am going to assume you are modifying their transforms, but you can add a reference for any Component type.)
The following will allow you to drag and drop the child elements in to the array on the prefab. From there you can modify them however you want in code.
public class MyObject : MonoBehaviour
{
[SerializeField] private Transform[] children;
public void Start()
{
// Modify each child Transform here ...
}
}