Cannot destroy the SphereCollider on Instantiated Objects
Hey,
I currently have made a script which instantiates 20 objects (stars). The issue is that I want to destroy then add a SphereCollider on each other objects but I can't got it to work. My function below:
public void SpawnStars() { //Debug.Log("The Size of the Array is " + SpawnPoints.Length); Vector3 randomPosition;
while (starscloned == false)
{
randomPosition = new Vector3(Random.Range(-400f, 400f), Random.Range(100f, 400f), Random.Range(-400f, 400f));
//The Vector called randomPosition is randomly assigned X, Y and Z co-ordinates by the "Random.Range" function.
// The generated Y co-ordinate must be between 0 and some number because a star can never be below the horizon.
//https://forum.unity3d.com/threads/randomly-generate-objects-inside-of-a-box.95088/
randomPosition = transform.TransformPoint(randomPosition * 2.5f);
// The randomPosition is maximised and scaled appropriate to the scene.
newClone = Instantiate (stars, randomPosition, SpawnPoints [spawnIndex].rotation);
//Instantiate generates a clone of an object. The function is divided into 3 components;
//Object, Position, Roation
//The object is the model which is being cloned
//The Position is the position where the object will be spawned
//Quaternion is the rotation component of the new spawn
newClone.name = ("StarClone" + spawnIndex);
sphereCollider = newClone.GetComponent<SphereCollider>();
sphereCollider.enabled = false;
Destroy(sphereCollider);
//newClone.AddComponent<SphereCollider> ();
//newClone.GetComponent<SphereCollider> ().enabled = true;
//newClone.GetComponent<SphereCollider> ().center = Vector3.zero;
//newClone.GetComponent<SphereCollider> ().radius = 1f;
// The new Object is intrinsictly named for future use
spawnIndex = spawnIndex + 1;
//Essentially a counter in itself
if (spawnIndex == SpawnPoints.Length) {
starscloned = true;
} else {
//other.Classify ();
}
}
//Debug.Log ("The clones have been created and the loop has been exited.");
}
Any idea's would be appreciated. Thanks heaps!
Answer by cclar202 · Dec 03, 2019 at 03:32 PM
I've successfully done this just with:
Destroy(gameObject.GetComponent());
Not sure why yours isn't working. Though you don't need to disable the collider on line 22, if you're just going to destroy it.,I've successfully done this just with:
Destroy(gameObject.GetComponent());
Your answer
Follow this Question
Related Questions
destroy asset is not permitted to avoid data loss? 0 Answers
I need help destroying a clone on function. 1 Answer
Bullet clones will not be destroyed. 2 Answers
Destroy the first instantiated clone after 4 have been instantiated 1 Answer
How to destroy a cloned/instantiated enemy from script? 0 Answers