- Home /
prefab clones not getting destroyed .
so this is my code .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class destroyobject : MonoBehaviour
{
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("1"))
{
this.gameObject.SetActive(false);
Debug.Log("Collide");
}
}
}
this is to destroy the gameobject on contact with another game object . the code for generating these multiple prefabs is :
using UnityEngine;
using System.Collections;
public class copy : MonoBehaviour
{
public Transform prefab;
void Start()
{
GameObject prefab = Resources.Load("Cube") as GameObject;
for (int i = 0; i < 100; i++)
{
GameObject go = Instantiate(prefab) as GameObject;
go.transform.position = new Vector3(0, i*6, 0);
}
}
void Update()
{
}
}
gameObject.SetActive(false);
does not destroy a game object, it will only deactivate it in the hierarchy. So all the components will stop running on it, including rendering, physics, and other scripts. Coroutines are also stopped.
To destroy a game object use Destroy(gameObject);
Also, it is recommended to avoid Resources.Load()
, it can cause various issues, usually memory leaks. You can use a member variable for your prefab and assign the Cube to it in the Editor. Or you can have a manager class that has a reference to the Cube prefab. Or if you want to be really fancy, then use a ScriptableObject that has a member variable referring the Cube, and assign the ScriptableObject to your copy script.
Example:
public class copy : $$anonymous$$onoBehaviour {
[SerializeField] private GameObject prefab = null; // assign Cube prefab to this in Editor
void Start () {
// no need for a local prefab variable, nor a call to Resources.Load();
for (int i = 0; i < 100; ++i) {
Instantiate(prefab, new Vector3(0, i * 6, 0), Quaternion.identity); // you can directly assign position in Instantiate
}
}
}
Answer by Harinezumi · Apr 26, 2018 at 09:06 AM
Based on the information in the comments, you would like to spawn a number of objects, destroy them when they collide with a "base" object, count the number of objects destroyed, and when that reaches a certain number, stop a timer that was started in the beginning (and possibly the simulation as well). Did I understand it correctly?
In case I did, the code you shared is mostly correct, but I suspect that the problem is that the collider on the object that has the Collide
script is not set to be a trigger, so OnTriggerEnter()
is never called, and/or that when you try to call Finnish
on a game object called "GameObject" either you don't find it, or it doesn't have a script which has a function with that name.
If this does not help, could you share what are the relevant objects (the base, cube, and timer I know about), and what components are on them?
absolutely correct.first il share the screenshot of the objects and then one more thing.
in this picture the base is the small light blue plate to the right of the white bowl . after co$$anonymous$$g in contact with this the object named 'cube' gonna get destroyed . gameobject contains the script for spawning multiple copies of the object . now whats happening is that i made certain tweaks in the timer script and here it goes..
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class timer : $$anonymous$$onoBehaviour {
public Text timerText;
private float startTime;
private bool finnished = false;
void Start()
{
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (finnished)
return;
float t = Time.time - startTime;
string $$anonymous$$utes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = $$anonymous$$utes + ":" + seconds;
if (score.scoreValue >= 2)
{
// GameObject.Find("GameObject").Send$$anonymous$$essage("Finnish");
GameObject.Find("cube").Send$$anonymous$$essage("Finnish");
}
}
void Finnish()
{
finnished = true;
timerText.color = Color.yellow;
}
}
there are no errors. also the color of the timer turns to yellow (thats alright) but the timer does not stop . any ideas ?
The line GameObject.Find("cube").Send$$anonymous$$essage("Finnish");
means "on the first game object with name "cube" that is found, call all the functions with the name "Finnish" in any script". However, I think your "cube" game object doesn't have that a script with that function, rather, you want to call it on a game object that has the timer script on it. Luckily for you, you are already in the timer script, so you can just say:
if (score.scoreValue >= 2) { // NOTE: you might want to change this to 3, because this will stop after 2 cubes destroyed
Finnish();
}
hey bro . it worked , i just called the Finnish() function inside the if statement in the timer class. so far so good . you all guys do stay put because only one thing remains in this project , that is related to Leap$$anonymous$$otion sensor . i'll need help when i come to that point . thank you guys so much , i'll see ya after sometime . adios . also share your thoughts regarding this project since it is made for rehab of stroke patients . thanks again..
oh yes and never$$anonymous$$d the triggers . i would like to work without them because on adding on trigger the objects behave in an erratic way .
Answer by NightmaresDev · Apr 25, 2018 at 09:30 AM
It seems that you are only Disabling the Object.
Try
Destroy(this.gameObject);
instead of
this.gameObject.SetActive(false);
now i am getting an error 'cannot cast from source to destination type'
From which line? Without context, we cannot help. $$anonymous$$oreover, that error cannot come from the code NightmareTD posted. Are you sure you replaced it in the code correctly? It should not have as GameObject
after it.
the code in which we instantiate the objects.
Answer by TauseefCVS · Apr 25, 2018 at 11:15 AM
you have the Rigidbody on one object because in collision one object must have rigidRigidbody to detect the collision between two colliders
Answer by vinilly · Apr 25, 2018 at 11:51 AM
You don't want to destroy the object with it's own script make it get destroyed by someone else collider.... reason the collision is "other" because it calls on the other collider.
This is to destroy self:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("1"))
{
Destroy(other.gameObject);
}
}
}
This is to destroy other colliding object
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("1"))
{
Destroy(other);
}
}
}
Please vote up to keep me around.
oh yess and one more thing . suppose that i wanna stop the timer at the time when 3 cubes(or any specific number of cubes) have been destroyed . can we do that ? much appreciated man
Try this code:
public class destroyObject : $$anonymous$$onoBehaviour {
private static int numDestroys = 0;
private void OnCollisionEnter (Collision other) {
if (other.gameObject.CompareTag("1")) {
Destroy(other.gameObject);
numDestroys++;
if (numDestroys >= 3) { Time.timeScale = 0; }
}
}
}
Destroy(other);
won't work, because it is of type Collision
, which does not derive of Component
.
I guess you meant Destroy(other.gameObject);
.
oh did i share the timer and collider script ? here it is .. this one is the timer .
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class timer : $$anonymous$$onoBehaviour {
public Text timerText;
private float startTime;
private bool finnished = false;
void Start()
{
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (finnished)
return;
float t = Time.time - startTime;
string $$anonymous$$utes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = $$anonymous$$utes + ":" + seconds;
}
public void Finnish()
{
finnished = true;
timerText.color = Color.yellow;
}
} and this one is kind of a collider or something that is to be added to the cube object . so with this what will happen is that when the number of collisions (ive called the number of collisions as 'score' in this )have equalled a certain number (for example 3) in this case then i will call the function Finnish() from the timer class .
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Collide : $$anonymous$$onoBehaviour {
private void OnTriggerEnter(Collider col)
{
if (score.scoreValue=='3')
{
GameObject.Find("GameObject").Send$$anonymous$$essage("Finnish");
}
}
}
all in all i wanna use thses to scripts to time my game and then stop the timer once the number of coilsions equals a fixed number .
p.s the code for the 'score' class is also given below.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class score : $$anonymous$$onoBehaviour {
public static int scoreValue = 0;
Text counter;
void Start()
{
counter = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
counter.text = "Failed Attempts: " + scoreValue;
}
}
the value of score is incremented on every collision . i hope i am making some sense. xD
Yes, now it makes more sense what you were talking about (I imagined that you have a collision counter system somewhere, but sharing this code is better).
For future questions, try to share all the relevant information from the start, that way you avoid misunderstandings and/or wasting time. You are also more likely to get responses and a correct answer sooner.
Btw, you can also edit your original question, adding this code to it, so everything is in one place.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161458im_/https://answers.unity.com/themes/thub/images/avi.jpg)