1
\$\begingroup\$

I have some issues for match the string and the InputField.text it's triggering multiple times after Active or dead Active Gameobject when press Submit button(in this case is "Cek Jawaban").

this my script

public void Answer(int index)
    {
        inputPanel.SetActive(true);

        inputField.text = "";

        inputPanel.transform.Find("KunciBtn").GetComponent<Button>().onClick.AddListener(() =>
        {
            if (inputField.text != "")
            {
                if (inputField.text == jawaban[index])
                {
                    Debug.Log("Right");
                }
                else
                {
                    Debug.Log("Wrong");

                }

                inputPanel.SetActive(false);
            }
            else
            {
                Debug.Log("jangan kosong");
            }
        });
    }

Many Buttons

enter image description here

enter image description here

as you can see on the console the first that trigger once but after second time its trigger twice.

\$\endgroup\$
2
  • \$\begingroup\$ how is answerPanel() being called? \$\endgroup\$
    – Charly
    Jun 29 '21 at 9:53
  • \$\begingroup\$ @Charly its on Button \$\endgroup\$ Jun 29 '21 at 10:02
3
\$\begingroup\$

There are 2 ways of giving functionality to the button: 1) via code; 2) using 'OnClick' feature within 'button' component in unity 'inspector' panel;

Here is the catch:

You are supposed to use ONE of these methods, NOT both of them.

Because button will fire all tasks assigned to it.

So, either assign functionality via code, - it should look something like this:

inputPanel.transform.Find("KunciBtn").GetComponent<Button>().onClick.AddListener(() => fireThisNiceFunction());

Or just use 'button' component in unity menu and assign your functionality that way. That's it!

If you choose to do it via code, - make sure that you assign listener only once! In your example you are actually assigning new listener every time button is clicked, so those listeners pile on top of each other.

p.s. Also you can wipe all button listeners clean by using

myNiceButton.GetComponent<Button>().onClick.RemoveAllListeners();
\$\endgroup\$
1
  • \$\begingroup\$ you are welcome! \$\endgroup\$
    – ShoulO
    Jun 29 '21 at 11:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .