- Home /
Switch the prefab of a game object from a script
If I drag&drop a prefab onto a gameobject in the hierarchy while holding the alt-key, the gameobject will be replaced with an instance of that prefab, while maintaining its name and transform. How can I do this in script?
Answer by DaveA · Apr 28, 2011 at 09:27 PM
http://www.unifycommunity.com/wiki/index.php?title=ReplaceSelection does something like this
The way that script works is by instantiating a new copy of the prefab, copying over the name and transform, and then destroying the object. Unfortunately, this won't work for me, as other objects are referencing the object to be replaced. Additionally, under some circumstances the prefab will be switched while the object is actively being moved, and even DestroyImmediate() won't destroy an object while it's being moved.
Answer by Myth · Apr 28, 2011 at 09:28 PM
leave the blank gameobject as a parent to the object you intend to replace.
when you wish to change it, have your script destroy the child object then:
instantiate the replacement,
parent
local rotation and local position set to "0"
and you're done
Your answer
Follow this Question
Related Questions
Is an object created when dragging a prefab to a GameObject script field 1 Answer
How to create and save a gameobject to a prefab with a script 3 Answers
Calling script on prefab using array of prefabs. 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Adding Prefab Components 1 Answer