• 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 Luckd93 · Dec 25, 2012 at 09:55 PM · variabledelay

delay and variable problem

Hello, I am new in unity3D, can somebody explain me why my program doesn't destroy the clone object and how instantiate an other new object automatically every 5 second??

 using UnityEngine;
 using System.Collections;
 
 public class cubelife : MonoBehaviour {
     public GameObject des;
     public Transform pref;
     public float t;
     GameObject clone;
     // Use this for initialization
     void Start () {
         Destroy(des,t);
         clone = Instantiate(pref, new Vector3(0,5,0),Quaternion.identity) as GameObject;
         }
     // Update is called once per frame
     void    Update () {
         if(Input.GetButtonDown("Fire1")){
             Destroy(clone,t);
             clone = Instantiate(pref, new Vector3(2,5,0),Quaternion.identity) as GameObject;
         }
         if(Input.GetButtonDown("Fire2")){
             Destroy(clone,t);
             clone = Instantiate(pref, new Vector3(-2,5,0),Quaternion.identity) as GameObject;
         }
     }
 }
Comment
Add comment · Show 8
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 Fattie · Dec 25, 2012 at 09:56 PM 0
Share

just FYI if you need to "delay", at first just learn to use the simple Invoke() command. unityGE$$anonymous$$S.com for details

avatar image Luckd93 · Dec 28, 2012 at 01:18 PM 0
Share

I tried to use waitforsecond but i have a problem with kind of function (void, Ienumerator, etc). Aldo Naletto with your edit nothing changed.

avatar image fafase · Dec 28, 2012 at 01:28 PM 0
Share

I would avoid the use of the same variable to destroy and create.

I would think it is somehow dangerous. clone is detroyed at the end of the frame since destroy is delayed and not done on the moment you call it, but in the meanwhile, you place a new reference in the same variable.

You could tru to have two different clone variable, and you always destroy one and add a new to the other.

avatar image Luckd93 · Dec 28, 2012 at 02:23 PM 0
Share

fafase I tried your proposal, but the problem is that nothing be save in clone.

avatar image fafase · Dec 28, 2012 at 02:28 PM 0
Share
 public class cubelife : $$anonymous$$onoBehaviour {
     GameObject[] clone = new GameObject[2];
     void Start () {
        Destroy(des,t);
        clone[0] = Instantiate(pref, new Vector3(0,5,0),Quaternion.identity) as GameObject;
    }
     void   Update () {
        if(Input.GetButtonDown("Fire1")){
          Destroy(clone[0],t);
          clone[1] = Instantiate(pref, new Vector3(2,5,0),Quaternion.identity) as GameObject;
        }
        else if(Input.GetButtonDown("Fire2")){
           Destroy(clone[1],t);
           clone[0] = Instantiate(pref, new Vector3(-2,5,0),Quaternion.identity) as GameObject;
        }
    }
 }

I remove the irrelevqnt lines but you need them obviously

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Geo.Ego · Dec 28, 2012 at 03:18 PM

First, to use WaitForSeconds for delay, your method needs to be an IEnumerator, and it needs to be called from StartCoroutine. You should read up on these topics:

MonoBehaviour.StartCoroutine

Essentially, just make your method "IEnumerator" instead of "void", use "WaitForSeconds" inside of it, and call it with "StartCoroutine", and you'll be golden. However, for this instance, we don't need it.

Next: when you Destroy an object, it and anything attached to it no longer exist. You Destroy clone, and then in the next line, you attempt to Instantiate it -- you can't do that. Once it's destroyed, it's destroyed. Instantiate is basically a copy and paste routine -- you can't copy it if it doesn't exist, and if you called Destroy on it, it doesn't exist. Also, when you Instantiate, you are placing a Transform in the first parameter of the method, which means you're just creating a new Transform, not the entire GameObject. I don't think this is what you want. Read up on Destroy() and Instantiate().

Object.Destroy

Object.Instantiate

It's important to understand the fundamentals of these methods and what ramifications they will have, as they are basic Unity3D methods that you will use over and over again to solve common problems. Understanding them will ensure that when you run into a problem, you know what tools to use to create a solution without nasty side effects or unwanted behaviour (like you're getting now).

Anyway, after reading up, we know that we cannot Destroy an object and then Instantiate it. So, let's keep a GameObject around in order to clone it. As far as automatically instantiating an object every five seconds, we can use the widely used "incrementing time via Time.deltaTime" method for that. Again, read up:

Time.deltaTime

Anyway, the following script will create the correct object when you click the fire buttons, and automatically create objects every five seconds below the two that you are creating manually. Please read the above portions of the documentation and note the comments in the script to truly understand what you are doing.

 using UnityEngine;
 using System.Collections;
 
 public class cubelife : MonoBehaviour
 {
     // Attach this script to an object (such as the camera) in your scene.
     
     public GameObject originalObject;            // Object that will be cloned. Drop a GameObject here in the Inspector.
     private GameObject clone;                    // Manually-created clone.
     private GameObject autoObject;                // Automatically created clone.
     private int numberOfCreatedObjects = 0;        // Number of times the script has created a clone automatically.
     private float instantiateTimer = 0;            // Timer for automatically creating clones.
     private float t = 0;                        // Time to wait before destroying an object.
     
     void Start ()
     {
         // When we start, we immediately clone the original object.
         clone = Instantiate (originalObject, new Vector3 (0, 5, 0), Quaternion.identity) as GameObject;
     }
 
     void Update ()
     {
         // To create a simple timer, increment a float value by Time.deltaTime each frame.
         instantiateTimer += Time.deltaTime;
         
         // When the timer reaches 5 seconds, do what you want it to do, and then reset it.
         if (instantiateTimer >= 5.0f)
         {
             // Keep track of how many times you have created an object.
             numberOfCreatedObjects++;
             
             // Use the value for the number of objects to offset each one on the x-axis.
             autoObject = Instantiate (originalObject, new Vector3 (numberOfCreatedObjects * 2, 3, 0), Quaternion.identity) as GameObject;
             
             // Reset your timer.
             instantiateTimer = 0;
         }
         
         // This part is basically unchanged, except that we're passing in the original object, not just a transform.
        if(Input.GetButtonDown("Fire1"))
         {
          Destroy(clone,t);
          clone = Instantiate(originalObject, new Vector3(2,5,0),Quaternion.identity) as GameObject;
        }
        if(Input.GetButtonDown("Fire2")){
          Destroy(clone,t);
          clone = Instantiate(originalObject, new Vector3(-2,5,0),Quaternion.identity) as GameObject;
        }
     }
 }

There are many ways to achieve what you're trying to achieve; many are better, but this is about as simple and straight-forward as it gets.

Comment
Add comment · Show 2 · 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 Geo.Ego · Dec 28, 2012 at 03:44 PM 0
Share

$$anonymous$$ake sure you are assigning the GameObject that you want to clone in the Inspector. Click the object with the script attached to it, and you'll see "Original Object" under the "Cubelife" script component in the Inspector. Drag the object you want to clone on to that field, then run your scene.

avatar image Luckd93 · Dec 28, 2012 at 04:22 PM 0
Share

Thx really much, you are really clear and useful.

avatar image
0

Answer by fafase · Dec 28, 2012 at 04:08 PM

Ok I got it working. I guess I needed to try.

 public class NewBehaviourScript : MonoBehaviour {
     public GameObject clone;
     public Transform pref;
     void Start(){
         clone = Instantiate(pref, new Vector3(0, 5, 0), Quaternion.identity) as GameObject;
     }
     void Update(){
         if (Input.GetButtonDown("Fire1")){
             var temp = clone;
             Destroy(temp,2f);
             clone =  Instantiate(pref, new Vector3(2, 5, 0), Quaternion.identity) as GameObject;
         }else if (Input.GetButtonDown("Fire2")){
             var temp = clone;
             Destroy(temp,2f);
             clone =  Instantiate(pref, new Vector3(-2, 5, 0), Quaternion.identity) as GameObject;
         }
     }
 }

The issue is you need to place your reference to an object inside another reference -temp- and destroy this one.

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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

12 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

Related Questions

Static variables 1 Answer

How do I make it so that it wont edit a variable again for a certain ammount of time? C# 3 Answers

Delaying a dynamic Variable(transform.position for Ex.) 2 Answers

Save/Load Variable with playerprefs 1 Answer

Random time interval 1 Answer


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