- Home /
Truly Truly (I really mean it) replacing a non-prefab GameObject
Hi,
I am working on a nested prefab system.
I want to replace a GameObject (which is not a prefab, I cannot make it a prefab because it is already a child of a big prefab) with a new one, not only just setting the data of transform to be the same as the old one, but also all the Monobehavior that refers to the GameObject are replaced as well (so after destroying the old GameObject will not result in a Missing GameObject error),
Is there actually a way to accomplish this?
Thanks
Answer by Fattie · Dec 29, 2015 at 03:39 PM
Any time you want, you can just (a) get rid of a game object (say, some character) and then (b) instantiate a new game object there (say, a new version of that character). Let's refer to the new object as
newRobot
.Be careful that you will probably want to set the parent properly in these cases.
I think you are asking: you have a number of other scripts which refer to
oldRobot
- what then happens? Unfortunately there is no possible magic solution here, quite simply you have to change those references tonewRobot
. How else could it be?
But note - of course, some script has to destroy the oldRobot and make the newRobot. Obviously, that script then "knows about" the newRobot
!! So it's a non-issue.
It could be the problem is you have some other scripts which also refer directly to the oldRobot
.
If so, that is basically your problem - you shouldn't do that.
Let's say that robotBoss
is the script instance which controls oldRobot
and later newRobot
. So, inside robotBoss
you have a variable robotBoss.theRobot
Quite simply, all your other scripts which for some reason need to refer to the (old or new) robot, should only be referring to robotBoss.theRobot
...
... they should not be directly connected to the robot.
Fortunately, the solution is that simple. Its' a general and very helpful software principle that you have a "single point" for anything (whether controlling something, accessing something, or whatever the case may be).
(Indeed more likely those other scripts would only use functions inside of robotBoss which asks robotBoss to do stuff in relation to the robot .. so, robotBoss.MakeRobotRun()
or robotBoss.RobotSoundEffects()
or whatever ... the other scripts would not directly talk to the robot.)
glad to have helped!
it's very likely you're looking for the "Grid" system in Unity ...
Here's a recent version of the "Grid" system ...
http://answers.unity3d.com/questions/663351/design-advice-power-up-system-static-variables.html
one of many questions discussing it ..
http://answers.unity3d.com/questions/551297/how-can-i-instantiate-a-prefab-from-a-static-funct.html
hope it helps!