Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Clone once a GameObject in OnEnable

Discussion in 'Scripting' started by AlexBecks27, Feb 13, 2018.

  1. AlexBecks27

    AlexBecks27

    Joined:
    Aug 8, 2017
    Posts:
    4
    I'm trying to instantiate a clone that follows a GameObject with an offset. As this GameObject is disabled and enabled in game I'm creating it in OnEnable like this:

    Code (CSharp):
    1. void OnEnable() {
    2.     CreateClone();
    3. }
    4.  
    5. private void CreateClone() {
    6.     GameObject clone = Instantiate(gameObject);
    7. }
    The problem is that this way it loops infinitely because clone will have the same script that will generate a new clone and so on... I tried disabling script and enabling after but it had no effect.

    How can I get only one clone each time the object is enabled?
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,156
    You could have a static variable that you set to true for example after you make your clone, then in OnEnable, if the value is true, don't create a clone.

    Not sure this is the best design pattern though honestly, but it will work.

    Another way is to keep a list on another script or a count, and check that to see if you have 2 objects already, if not, don't clone.

    The basic idea, no matter what you choose to do is to track that you have created a clone and don't create another if you have.
     
  3. AlexBecks27

    AlexBecks27

    Joined:
    Aug 8, 2017
    Posts:
    4
    The static variable is a better solution for me, thanks for helping :)