- Home /
Adding Prefab Components
I need to add a prefab gameobject as a component to another gameobject via scripting, but am having problems. I've tried using the AddComponent function and been able to add blank gameobjects this way. I've also been able to add various custom scripts this way. However, I have been completely unable to add prefab gameobjects in this fashion. Neither a type parameter nor a string parameter will find any prefabs, and AddComponent won't take straight references (unlike Instantiate).
This is a major problem for my project; it seems like prefab components ought to be a logical, integral functionality of unity's prefab system, but I cannot find a command to make it work. Does anyone know how to do this?
Thanks,
C.
Answer by PrimeDerektive · Sep 09, 2011 at 08:26 PM
A Prefab is a GameObject. a Component is anything (MonoBehaviours mostly) that attaches to GameObjects. Therefore, a Prefab cannot be a Component, and could never be used as a parameter in AddComponent().
Are you confusing "adding a Prefab to a GameObject" with parenting a prefab to a GameObject? Because that's as simple as setting the transform.parent, eg:
myNewObject : GameObject = Instantiate(myPrefab, pos, rot);
myNewObject.transform.parent = gameObjectIWantToParentTo.transform;
This is correct, thanks. I was confused about the difference between the two types of hierarchy.
However, I have a related problem: I don't want or need to instantiate the modular object at the time of assembly. I just need to store it for later access and instantiating. Setting a prefab's parent obviously doesn't work, but instantiating before setting the parent relationship is undesirable. Would you happen to know if there is a way to create a gameobject, without instantiating it in the scene, that is a copy of a prefab?
Right now I'm setting up scripts that will store assembly info, then recreate the object when needed. It would be far more elegant to store complete GameObject references.
Thanks,
C.