- Home /
Instantiating a prefab/declaring a parent
When my character controller walks over a gameObject on the ground, I am destroying it and then instantiating it on a gameobject child of my character controller.
I got pretty much everything to work expect the gun would instantiate not at the point of the transform, but the prefab transform position. I was getting the "can't set parent as transform of a prefab" console error. I also couldn't drag the scene object into the transform field in inspector. After some research, both reasons make sense.
However, I am not sure how to do it? I think the path forward is to instantiate the player and then when I instantiate the gameobject (gun), also destroy and re-instantiate the "weaponHolder" gameobject. But then I have to set the parent of that and then it seems like I'm in a loop. So, any help is appreciated.
Edit: Just used weaponHolder = GameObject.Find("WeaponHolder"); to get the instantiated gameObject.
Answer by RX187 · Aug 31, 2018 at 12:30 AM
@xrenuix Can you post part of the code? would make things easier to understand but from what I understand you would need to do this:
https://docs.unity3d.com/ScriptReference/Transform.SetParent.html
And with that something similar to this:
public GameObject weaponHolder;
public GameObject gunPrefab;
public void DoSomething()
{
weaponHolder = GameObject.Find("Weapon Holder");
GameObject obj = Instantiate(gunPrefab);
obj.transform.SetParent(weaponHolder.transform, false);
}
You need to make it work for your case but that's how you can get the weaponHolder and then make it a parent to the gunPrefab;
Yep, that's exactly what I needed. Wasn't familiar with "GameObject.Find". I feel like that's super useful, but I just hadn't learned it yet.
Your answer
Follow this Question
Related Questions
Keep instantiated GameObject's position while parenting it to another GameObject 3 Answers
Duplicate UI object 2 Answers
Parenting instantiated particle system 1 Answer
Error : Transform.parent not working properly. 1 Answer
Silly Instantiation Issue 0 Answers