I am trying to create “a prefab” in script, so I can Instantiate it freely whenever I want. To be specific, I have a Unity prefab “Player” → that should be a tank with two parts - body and gun. So I have also prefabs of many Bodies and many Guns so player can choose from those. Now I want to create something like playerPrefab object in script, whose instantiated gameobject will contain all those parts.
For now it looks like this:
GameObject playerPrefab = ... GameObject playerPrefabBody = ... GameObject playerPrefabGun = ... playerPrefabBody.transform.parent = playerPrefab.transform; playerPrefabGun.transform.parent = playerPrefab.transform; ..... GameObject player = Instantiate (playerPrefab, ...);
I’m still getting this:
Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption (GameObject: 'Body 2'). UnityEngine.Transform:set_parent(Transform)
I was googling a bit, but hadn’t found anything useful. I know, I can instantiate all three prefabs and THEN join them, but that would be ugly, as i will need to do that every time player is beeing spawned (which could be once each 5 seconds, or even less. Well, that sould not pose any problem, but it’s still ugly )
Just to point out, I don’t really want to change the prefab itself, as it will be used for the same player, when he chooses other type of Body or Gun…
Is there any way to do this as described?