- Home /
How to create a duplicate of an object after a specific time with the same starting properties?
Please read carefully and help me
Now I have a visible bullet which is the child of a gun and its position is attached to the end point of the gun(as the player moves the gun, the bullet also moves) now when the player clicks, the bullet is released from the point and is no longer the child of the gun(I had to detach the parent/child relationship because the bullet was still moving with the mouse cursor when it was in the air). Now the bullet hits the target(it is a big bullet so it is visible), as soon as it hits the target I do not want to bother the released bullet anymore, all I need is the copy of the same bullet but in a way that it was all in the very beginning, i-e a new bullet reattaches to the parent, it appears exactly at the point of its parent and again moves with the cursor of the parent, in the same time the prereleased bullet is still visible somewhere in the ground(unattached to the parent) where it was lying after hitting the targer....
So in brief, all I want is the duplication of an object but with the same properties as it was in the beginning.
You can also mention if there is a way that the first bullet after hitting the target or after a delay of a specific time like 20 seconds come again to the point of the gun and establishes its relation with its parent again(because after having so many duplicates the game starts to lag), Either way it is suitable please help me solve the problem because currently what I am doing is, I have made a lot of duplicates already in the hierarchy and I get them checked one by one after a several time so it's limited and very lengthy and inappropriate.
Please let me know if there is any solution...
Answer by logicandchaos · Apr 25, 2020 at 01:23 PM
Make a prefab of the object you want to copy, then use instantiate.. but from the rest of your post that is not what you want, you want object pooling, so all your bullets will already be created when your game starts in a list, this is the pool. You have them all not active, when you want to shoot instead of creating a new bullet you take one from the pool and then remove it from the pool, activate it, set it's transform.position to the gun barrel and when it hits something you deactivate it again and add it to the pool. This can be achieved easily in unity using OnEnable and OnDisable. class BulletPool:MonoBehaviour { public List bulletPool; }
class Bullet:MonoBehaviour
{
void OnEnable()
{
if(BulletPool.bulletPool.Contains(this))
BulletPool.bulletPool.Remove(this);
}
void OnDisable()
{
if(!BulletPool.bulletPool.Contains(this))
BulletPool.bulletPool.Add(this);
}
}
That should get you started look into object pooling.