Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by rtanwar616 · Apr 25, 2018 at 08:49 AM · unity 5c# tutorial

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()
     {
 
     }
 }
Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Harinezumi · Apr 25, 2018 at 09:30 AM 0
Share

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
         }
     }
 
 }

4 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

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?

Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rtanwar616 · Apr 26, 2018 at 09:28 AM 0
Share

absolutely correct.first il share the screenshot of the objects and then one more thing.alt text

1.png (471.3 kB)
avatar image rtanwar616 · Apr 26, 2018 at 09:34 AM 0
Share

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 ?

avatar image Harinezumi rtanwar616 · Apr 26, 2018 at 09:40 AM 0
Share

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();
 }
avatar image rtanwar616 Harinezumi · Apr 26, 2018 at 09:56 AM 0
Share

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..

Show more comments
avatar image rtanwar616 · Apr 26, 2018 at 09:38 AM 0
Share

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 .

avatar image
2

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);
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rtanwar616 · Apr 25, 2018 at 10:16 AM 0
Share

now i am getting an error 'cannot cast from source to destination type'

avatar image Harinezumi rtanwar616 · Apr 25, 2018 at 10:22 AM 0
Share

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.

avatar image rtanwar616 Harinezumi · Apr 25, 2018 at 10:35 AM 0
Share

the code in which we instantiate the objects.

avatar image rtanwar616 rtanwar616 · Apr 25, 2018 at 10:30 AM 0
Share

alt text

6.png (19.9 kB)
avatar image
1

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

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.

Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rtanwar616 · Apr 25, 2018 at 11:54 AM 0
Share

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

avatar image vinilly rtanwar616 · Apr 25, 2018 at 12:16 PM 0
Share

You're in safe hands @Harinezumi is the best

avatar image Harinezumi rtanwar616 · Apr 25, 2018 at 12:24 PM 0
Share

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; }
         }
     }
 
 }
avatar image Harinezumi · Apr 25, 2018 at 12:13 PM 1
Share

Destroy(other); won't work, because it is of type Collision, which does not derive of Component.
I guess you meant Destroy(other.gameObject);.

avatar image vinilly Harinezumi · Apr 25, 2018 at 12:16 PM 0
Share

Thank you you're back sorry I need sleep :D

avatar image rtanwar616 vinilly · Apr 26, 2018 at 05:53 AM 0
Share

good morning everyone

avatar image rtanwar616 Harinezumi · Apr 26, 2018 at 08:27 AM 1
Share

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

avatar image Harinezumi rtanwar616 · Apr 26, 2018 at 08:40 AM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

166 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How do I change the speed at which the slider moves? 5 Answers

please help, i have had this erroe for a long time:,Please help, i have had this issue for a long time. here is the error 0 Answers

Making a dynamic radar type graph 3 Answers

How to save coins with PlayerPrefs 2 Answers

How do I make script in C# the result will execute if all the boxes is fill up? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges