- Home /
restricting clone number
im having a problem with this script sometimes making my gameobject clone to many times, how can i make it restrict to only cloning 1 time? using System.Collections; using System.Collections.Generic; using UnityEngine;
public class destructible : MonoBehaviour {
public GameObject debrisPrefab;
public float strength;
void OnMouseDown() {
DestroyMe ();
}
void OnCollisionEnter(Collision collision ) {
if (collision.impactForceSum.magnitude > strength) {
DestroyMe ();
}
}
void DestroyMe () {
if (debrisPrefab) {
Instantiate (debrisPrefab, transform.position, transform.rotation);
}
Destroy (gameObject);
}
}
Answer by davidcox70 · Apr 09, 2018 at 11:11 PM
Perhaps what is happening is that the OnCollisionEnter event is firing many times as it collides. This would trigger your DestroyMe script many times, which in turn might be making multiple instantiates.
Try adding a private bool isCloned at the beginning, and then;
void DestroyMe () {
if (debrisPrefab && !isCloned) {
Instantiate (debrisPrefab, transform.position, transform.rotation);
}
isCloned=true;
Destroy (gameObject);
}
This should ensure the Instantiate line can only run once.
ya thanks man ill try it out, i have a tornado game and the tornado picks up tones of objects and when it hits my house it duplicates a shattered version of the house, becasue the house has at least 50 mesh colliders if many of the colliders are hit by an object at the same time it dipplicates it that many times
do i need to make isCloned an int or public float or something?
Answer by Jdogmaster · Apr 09, 2018 at 11:32 PM
im getting an error with the "isCloned" public GameObject debrisPrefab; public float strength;
void OnMouseDown() {
DestroyMe ();
}
void OnCollisionEnter(Collision collision ) {
if (collision.relativeVelocity.magnitude > strength) {
DestroyMe ();
}
}
void DestroyMe () {
if (debrisPrefab && !isCloned) {
Instantiate (debrisPrefab, transform.position, transform.rotation);
}
isCloned = true;
Destroy (gameObject);
}
You'll need to define your isCloned at the beginning;
private bool isCloned;
it works perfect now man thx again been trying to fix this problem like all day and turns out its just that simple :D
Your answer
Follow this Question
Related Questions
Destroy a specific instantiated clone? 2 Answers
How can I destroy my Instance without renaming it? 2 Answers
Instantiate and Destroy an object while crossing a line with its clone also 1 Answer
Destroy multiple instances of an object 1 Answer
Trying to Instantiate() an object without cloning the code 2 Answers