- Home /
Instantiating infinity copies of the same prefab?
Hi.
I came across this issue, when I tried to make a simple script that instantiates a different object and destroys the current object when the player is close enough. The instantiate function keeps instantiating new copies of the same object (when called in the Update() function), even after the object is destroyed. Would calling instantiate in a different function react differently?
EDIT: Calling instantiate in a different function, rather than Update() has the same result. Here is my script (JavaScript):
public enum typeOfDectruction {destroyOnly, destroySound, destroyReplace, destroyReplaceSound}
var destructionType : typeOfDectruction;
var replacementPrefab : Transform;
var soundObjectPrefab : Transform;
var distanceToDestroy : float = 5;
var objectToDestroy : Transform;
var playerCamera : Transform;
function Update () {
var dist = Vector3.Distance(objectToDestroy.position, playerCamera.position);
if(destructionType == typeOfDectruction.destroyReplaceSound) {
if(dist < distanceToDestroy) {
DestroyReplaceSound();
}
}
if(destructionType == typeOfDectruction.destroyReplace) {
if(dist < distanceToDestroy) {
DestroyReplace();
}
}
if(destructionType == typeOfDectruction.destroySound) {
if(dist < distanceToDestroy) {
DestroySound();
}
}
if(destructionType == typeOfDectruction.destroyOnly) {
if(dist < distanceToDestroy) {
DestroyOnly();
}
}
}
function DestroyOnly () {
Destroy(objectToDestroy);
}
function DestroySound () {
Instantiate(soundObjectPrefab, transform.position, transform.rotation);
Destroy(objectToDestroy);
}
function DestroyReplace () {
Instantiate(replacementPrefab, transform.position, transform.rotation);
Destroy(objectToDestroy);
}
function DestroyReplaceSound () {
Instantiate(replacementPrefab, transform.position, transform.rotation);
Instantiate(soundObjectPrefab, transform.position, transform.rotation);
Destroy(objectToDestroy);
}
Would help to know how exactly you are doing it right now.
even after the object is destroyed
Are you quite sure of that? This is probably a good time to paste in some code we can troubleshoot. If you can't figure out the formatting, here, there is always Pastebin.
Answer by Piflik · May 10, 2012 at 06:21 PM
Don't know what objectToDestroy references, but I guess it is not the object calling the function. Try
Destroy(gameObject);