0
votes

I have a prefab, which has a script component as MonoBehaviour. This script has 3 public fields as text; which are assigned in the inspector, before saving the gameobject and remove it from the scene.

Now, this works fine if I have a UI element, like a panel. Every text field on the panel, defined in the prefab, is still assigned when the prefab is instantiated at runtime.

This sadly does not work on another prefab that I have made; which is not a UI element. In my case it is a meshgameobject with various components on it (navmesh agent, capsule collider, rigidbody, animator and so on)

I believe this is due the fact that with the UI panel, the elements are already in the gameobject hierarchy, while when the reference is on a different gameobject; Unity does not keep track of them.

This means that I have to always add at runtime via code, the elements that I want to reference on each prefab, if they are not part of the game object itself? In this case I would just avoid to have my references public then, since I won't be using the inspector in this case (every gameobject of this type is instantiated at runtime).

Just checking if there is any other solution to work around this.

2
You can always find your UI elements using FindObjectWithName - libertylocked
Yes, but that defy the purpose of making fields public and use the editor to add references. In my mind, everyting done in the editor is persisiting when you create a prefab; instead it doesn't work in that way most of the time. - user393267

2 Answers

0
votes

Use List to save reference for each generated object. Lets assume that the object you want to add to store the reference is called meshgameobject.

Example:

List<meshgameobject> meshGOB;

initiaize inside Start function

void Start(){
 meshGOB = new List <meshgameobject>();
}

Then create and use list.add() to add reference during runtime like

meshGOB.Add((meshgameobject)Instantiate(prefab, Pos, Quaternion.Identity);

OR

meshgameobject tempGOB= (meshgameobject)Instantiate(prefab, Pos, Quaternion.Identity);

//Do something with meshgameobject

tempGOB.someAction......

then add the reference to the List

meshGOB.Add(tempGOB);
0
votes

Do not make a perfab which references to other gameobjects in the scene but are not in the hierarchy of the perfabI itself. AFAIK, Unity can not track this kind of references. Even if Unity supported this kind of prefab, you could not use this kind of prefab in other scenes because the specific references, so it is not make much sense to make a perfab like that. If you have to make it a pefab just because the scene and the game object are maintained by different person, you may use Find() to populate the references at runtime.