- Home /
I need to Instantiate a prefab at the same location where a different object was destroyed.,
This is my script so far. Instead of creating object b where object a was destroyed, it creates it at object a's last position before it was destroyed. Any ideas on what I'm doing wrong?
,
Answer by Cornelis-de-Jager · Apr 12, 2018 at 02:31 AM
You can use the script below:
void OnTriggerEnter (Collider other) {
if (other.gameObject.tag == "Plys2") {
Vector3 spawnLoc = other.ClosestPoint (transform.position);
Quaternion spawnRot = objToDestroy.transform.rotation;
Instantiate (objToSpawn, spawnLoc, spawnRot);
Destroy(objToDestroy);
}
}
Good day, your answer is correct, (upvoted) but as a good practice, if you want to "replace" an object for another, once you know the position is better to destroy the 1st object and then instantiate the 2nd, so i reccomend to swap the las 2 lines
Destroy(objToDestroy);
Instantiate (objToSpawn, spawnLoc, spawnRot);
Bye!
It doesn't make any difference at all.
Depending on the objects and the number, is always better to reduce number of elements that increase them. I say is a good practice, not incorrect. Imagine doing this in a lot of elements at same time, is better to reduce number of elements and then increase, than increase them and then reduce. Number of elements active at same time will be lower.
But as i said, your answer is 100% correct :D