Instantiate without creating clone
Hello, I would like create and spawn a GameObject directly from my code to the scene. I read that if I wanted to do that, I should use Instantiate(). My issue with this though is that it's creating a clone, which I don't need. I simply want to spawn the original GameObject into the scene.
void createFairy()
{
if (Input.GetKey(KeyCode.F))
{
GameObject objectToCreate = swap.getPlayables();
objectToCreate = Instantiate(new GameObject("Fairy"));
objectToCreate.tag = "Playables";
//Instantiate(objectToCreate);
}
}
This is what I get when I press the F button:
Thanks in advance for the help!
if(gameObject.name == "fairy(Clone)"){ Destroy(gameObject);
. You can use if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.F))
{ Instantiate(Gameobject,transform.position.transform.rotation); }
I think you should fix the actual problem of creating 2 objects ins$$anonymous$$d of just removing the extra copy. Look at @DiegoSLTS answer @Squishyaura
Answer by DiegoSLTS · Aug 28, 2016 at 05:09 PM
"new GameObject()" already instantiates the GameObject in the scene, and Instantiate makes a copy of whatever you pass to it. You have the Fairy and the clone because you're telling Unity to create the Fairy (with new GameObject("Fairy");) and then make a copy of it (with Instantiate).
Just remove the "Instantiate":
void createFairy()
{
if (Input.GetKey(KeyCode.F))
{
GameObject fairy = new GameObject("Fairy");
fairy.tag = "Playables";
}
}
Need Help! using this method creates a object in scene but its an empty object with transform component not the prefab that i want to create!
This question was about creating an empty GameObject, what you're trying to do is different. Just use Instantiate and pass the prefab reference as the first argument.
Answer by ReggieBeRetro · Aug 29, 2016 at 10:06 PM
or change the name after it is instantiated.
objectToCreate.name = "NewFariy_Obj" + spawned;
spawned++;