Search Unity

Instantiate PROBLEM !!

Discussion in '2D' started by anubhav01, Mar 7, 2019.

  1. anubhav01

    anubhav01

    Joined:
    Feb 20, 2018
    Posts:
    3
    Hi,
    I am creating a 2D game (with the 2D tempelate).
    I want to spawn an object and for which I am using the following script.
    The script is attached to the object from which I want it to be spawned.
    But, when I run the game 3-4 objects spawn instead of 1.
    Please help me out. ASAP

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerSpawn : MonoBehaviour {
    6.  
    7.     public Transform spawnPoint;
    8.     public GameObject playerPrefab;
    9.  
    10.     // Update is called once per frame
    11.     void Update () {
    12.      
    13.         if(Input.GetKey(KeyCode.A))
    14.         {
    15.             Spawn();
    16.         }
    17.     }
    18.  
    19.     void Spawn()
    20.     {
    21.         Instantiate(playerPrefab, spawnPoint.position, spawnPoint.rotation);
    22.     }
    23. }
    24.  
     
    Last edited: Mar 7, 2019
  2. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    You have this running in update and using GetKey that means it is going to spawn stuff really fast while you hold the button down. Use GetKeyDown or GetKeyUP not getkey.