Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to create only one Clone with Instantiate in Start()

Discussion in 'Scripting' started by RokoBa2, Jan 8, 2021.

  1. RokoBa2

    RokoBa2

    Joined:
    Dec 28, 2020
    Posts:
    2
    Hello, how do I create only one clone with Instantiate?
    Always when I hit start ther are continuesly spawning apples on my screen. But I only want one clone.
    This is my code:
    Code (CSharp):
    1. public class applespawn : MonoBehaviour
    2. {
    3.     public Transform prefab;
    4.     // Start is called before the first frame update
    5.     void Start()
    6.     {
    7.         float posx = Random.Range(-8.0f, 6.0f);
    8.         float posy = Random.Range(-4.0f, 4.0f);
    9.         this.transform.position = new Vector2(posx, posy);
    10.  
    11.         float lposx = Random.Range(-8.0f, 6.0f);
    12.         float lposy = Random.Range(-4.0f, 4.0f);
    13.         Instantiate(prefab, new Vector3(lposx, lposy, 0), Quaternion.identity);
    14.     }
    15. }
    16.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,893
    Does your apple prefab have this "applespawn" script on it?

    If so, every time you spawn an apple, that apple is going to spawn a new apple, because of this script, and so on forever.

    Take this script off your apple prefab, and put it on a different object.
     
    Joe-Censored and RokoBa2 like this.
  3. RokoBa2

    RokoBa2

    Joined:
    Dec 28, 2020
    Posts:
    2
    Oh..... Thank you, im new to Unity xD
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You could also track how many instances of this class exist using a static variable. Increase in Awake for every new one, in OnDestroy you decrease. Then you can decide based on the current number if you should instantiate more. But for you use case, @PraetorBlue is giving you better advice.