Search code examples
c#unity-game-enginespawngameobject

Spawn a single object in Unity on click


I want to spawn a single game object either when I click on the screen. I have tried using loop but still it instantiate more than one time. Here I have used other loop too and tried to put it in Start method too... I have followed many youtube video but couldn't get the desired output.

[SerializeField]
GameObject spawnObject;

void Update()
{
    for (int i = 0; i < 1; i++)
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            GameObject g = Instantiate(spawnObject, (Vector2)touchPos, Quaternion.identity);
            //Debug.Log(i);
            Debug.Log(Input.mousePosition);
        }
    }
}

Help me out...


Solution

  • If you want to limit this for the entire live time of the application

    • Either simply add a flag like

      [SerializeField]
      GameObject spawnObject;
      
      private static bool wasSpawned;
      
      void Update()
      {
          if (!wasSpawned && Input.GetMouseButtonDown(0))
          {
              Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
              GameObject g = Instantiate(spawnObject, (Vector2)touchPos, Quaternion.identity);
              Debug.Log(Input.mousePosition);
      
              wasSpawned = true;
          }
      }
      
    • or you could as well simply deactivate/destroy this component so it isn't further executed at all which would even slightly save some resources

      [SerializeField]
      GameObject spawnObject;
      
      void Update()
      {
          if (Input.GetMouseButtonDown(0))
          {
              Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
              GameObject g = Instantiate(spawnObject, (Vector2)touchPos, Quaternion.identity);
              Debug.Log(Input.mousePosition);
      
              // destroys only this component, not the entire GameObject 
              Destroy(this);
              // alternatively destroy entire GameObject
              //Destroy(gameObject);
              // alternatively only disable in case needed again later
              //enabled = false;
          }
      }