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

GetButtonDown question, Creates multiple objects?

Discussion in 'Scripting' started by mehware, Nov 29, 2007.

  1. mehware

    mehware

    Joined:
    Nov 19, 2007
    Posts:
    739
    I am trying to create a crate where the mouse position is when I click the mouse button. Here is the code for it.

    Code (csharp):
    1.  
    2. if (Input.GetButtonDown("Fire1")) {
    3.            
    4.             var pos = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
    5.             Instantiate(crate, Vector3(pos.x, pos.y, 0), transform.rotation);
    6. }
    7.  
    Why does it create two crates. I just want one!
     
  2. mehware

    mehware

    Joined:
    Nov 19, 2007
    Posts:
    739
    hmm for some reason if I check IsKinematic on the rigid body ( the crate ) it only makes one of these. I don't know why though.
     
  3. mehware

    mehware

    Joined:
    Nov 19, 2007
    Posts:
    739
    I found out why it creates two crates. I *think* when you do Input.GetButtonDown("fire1") it could register twice if you hold it down long enough. Adding


    Code (csharp):
    1.  
    2. Input.ResetInputAxes();
    3.  
    after the if statement fixes this.
     
  4. DannyJ

    DannyJ

    Joined:
    Sep 3, 2007
    Posts:
    40
    I discovered that GetButtonDown registers once per frame so it can register multiple times if it is used within a FixedUpdate loop or in a while loop that uses yield WaitForFixedUpdate ().

    The solution is to use Update () or yield when checking for GetButtonDown.
     
  5. mehware

    mehware

    Joined:
    Nov 19, 2007
    Posts:
    739
    Im using it in OnGui().
     
  6. forestjohnson

    forestjohnson

    Joined:
    Oct 1, 2005
    Posts:
    1,370
    OnGUI cane be called multiple times per frame. Its better if in OnGUI you set a flag to be dealt with next frame.

    Code (csharp):
    1.  
    2. private var createCrate = false;
    3.  
    4. function OnGUI ()
    5. {
    6.     if(GUILayout.Button("hai"))
    7.     {
    8.         createCrate = true;
    9.     }
    10. }
    11.  
    12. function Update()
    13. {
    14.     if(createCrate)
    15.     {
    16.         createCrate = false;
    17.         // do the crate creation
    18.     }
    19. }
    20.