0
\$\begingroup\$

I need help. When I click a Button, I want to create a new Button. My code, however, creates four Buttons. What should I do?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;

public class AddButton : MonoBehaviour
{
    public GameObject prefabButton;
    public RectTransform ParentPanel;
    public Button saveButton;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
           // for (int i = 0; i < 2; i++)
            {
                GameObject button = (GameObject)Instantiate(prefabButton) as GameObject;
                button.transform.SetParent(ParentPanel, false);
                button.transform.localScale = new Vector3(1, 1, 1);
             }
        }  
    }
}
\$\endgroup\$
1
\$\begingroup\$

Input.GetMouseButton(0) will return true during every frame where you keep holding the button. Unity frames are quite fast, so it requires quite a lot of agility to hold a button for just one frame.

Try Input.GetMouseButtonDown(0) instead. It only returns true during the first update of a click.

By the way: Your code will spawn a new button no matter where you click, because it just detects mouse clicks, not where these clicks happen. If you want an event to happen when a button is clicked, you shouldn't use the Input class. Add a method as an event handler for that button, instead. You can do that in the editor or with a script.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.