- Home /
Instantiate problem
i want to swap objects using instantiate.
im having trouble using instantiate, could someone help me with the code.
var pos : Rect; var newObj = Instantiate("The new 3d Object");
function OnGUI()
{
if (GUI.RepeatButton(pos, "Bodyconditionscore 2"))
{
newObj.transform.parent = oldObj.transform.parent;
Destroy("My old 3d object");
}
}
greetz,
What is the outcome of your code? Where is oldObj defined? Does oldObj has a parent?
the old obj is in the gamescene and needs te be destroyed completely: the parent with children etc. and a new object needs te be exactly in the same spot where the old object was
Answer by spinaljack · Jun 08, 2010 at 01:22 PM
When you instantiate with just a prefab it'll appear at the location that you saved it in (could be anywhere). When you use transform.parent it changes the parenting of the object but it wont move to where the old object was.
What you need to do is instantiate the new object at the same transform.position (or alter it's position afterwards, which ever you prefer).
At the moment I'm assuming your old object gets destroyed and then you can't find the new object because it appeared else where.
Do something like this:
function OnGUI()
{
if (GUI.RepeatButton(pos, "Bodyconditionscore 2"))
{
var newObj = Instantiate(objPrefab, oldObj.transform.position , oldObj.transform.rotation);
newObj.transform.parent = oldObj.transform.parent;
Destroy(oldObj);
}
}
i tried this code but do i need to create some new variables. ??? cuz im getting some errors?
Yes, you need to add your own header with all the variables declared. objPrefab is type GameObject where you drag the prefab onto in the spector. oldObj is the thing you're replacing.
Your answer
Follow this Question
Related Questions
swap objects with instantiate 2 Answers
[SOLVED] Only instantiating once 1 Answer
problem with instantiate 3 Answers
copy settings from other gameobject 2 Answers