- Home /
how to duplicate a gameobject using scripting?
Hi everyone,
I am making one infinite runner game. In that game I am generating many obstacles, bonuses etc. Can anybody tell me how to duplicate a transform or gameobject. I need the script without Instantiate method. if any method exists for duplicating a gameobject please let me know.
Actually what I am trying to do is instantiating takes some time. If I duplicate an already instantiated gameobject I just need to make a clone of it instead of reinitiating a similar gameobject or maintaining an object pool before loading the scene
Answer by Bunny83 · Jul 26, 2013 at 11:05 AM
Instantiate IS the duplicate command in Unity. If the object is compilcated (with lots of childs, meshes, ...) it will take some time. there's no way around that.
See those pages: Instantiate Prefabs and Instantiate.
If Instantiate is too slow for you, you should instantiate all at the beginning and just move / enable / disable them as you need them.
Thanks for your answer. Currently I am keeping an object pool and enabling and disabling gameobjects. I think this is the fastest way.
Well, it depends on your platform. In my tests enabling and disabling objects was actually as slow as Instantiate and Destroy on my Nexus7. I guess this was mainly because my objects have $$anonymous$$eshColliders. If you enable or disable $$anonymous$$eshColliders Unity has to update it's physics system which could take a while.
For an endless game you could simply try to keep the sections enabled and just move them ahead when needed. Since passed sections are behind the camera they are frustum culled anyways. Of course they still require some processing, but it makes the "instantiating" faster.
If you instantiate an object it also has to update the physics system. So it does the same thing AND creates the gameobject. I'd like to see your tests and the results, because I don't see how it's possible that it would take longer
Answer by whosdoom · Nov 18, 2020 at 07:33 AM
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MakeEnemy : MonoBehaviour {
public GameObject enemyMake;
void Start () {
nasru = 3;
}
float aralik;
void Update () {
nasru -= Time.deltaTime;
if(nasru <= 0)
{
nasru = 3;
GameObject go = GameObject.Instantiate(enemyMake);
go.transform.position = transform.position;
}
}
}
add that code to the plane. The enemy will created at the origin of the plane.
Your answer
![](https://koobas.hobune.stream/wayback/20220613110915im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to identify a different camera? Urgent 1 Answer
Problem accessing C# from Javascript 1 Answer
More elegant use of struct and class 1 Answer
Accessing to a Scriptable object from another script 1 Answer
shot delay in between bullets 1 Answer