1

I am using Unity 5. There are 2 Buttons in a Canvas - YesButton & NoButton. I added only one script called "ButtonScript.cs" in both buttons as a component.

I need -

  1. While pressing in YesButton, Debug.Log("Yes");
  2. While pressing in NoButton, Debug.Log("No");

What should I write in my script?

3 Answers 3

1

There is many way to do that but i mostly use this one...

public void buttonDownEvent(BaseEventData eventData){

    if (eventData.selectedObject == null)
        return;

    string textCheck = eventData.selectedObject.name;

    switch (textCheck) {

     case "Yes":
        Debug.Log(textCheck); // OutPut is YES;
        break;
     case "NO":
        Debug.Log(textCheck); // OutPut is NO;
        break;
     default:
        break;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ajay kumar.
0

The easiest way to do this is have a parameter passed into the method you want to call OnClick, so in your ButtonScript.cs file - you can have something like this

public void ClickLog(string theWord)
{
    Debug.Log(theWord);
}

When you attach this method to the OnClick of the buttons, you can input what you want to pass into the method through the editor.

In the case that the Buttons are being created in code - you can add parameters to OnClick events like so

//Button called newButton
UnityEngine.Events.UnityAction action1 = () => { ButtonScript.ClickLog("Yes"/*or "No"*/); };
 newButton.onClick.AddListener(action1);

1 Comment

IMO it would be easier to just use generic form of UnityAction like UnityAction<string>.
0

There are many ways to solve this. First one is taht you can operate on Tags:

Debug.Log(gameObject.Tag == "YesButton" ? "Yes" : "No");

But (imo) dealing with tags is painfull so the easiest way would be to just make some enumeration (for future improvements like "Yes", "No", "Cancel" etc.)

public enum ButtonType : byte {
    YES = 0,
    NO = (1 << 0)
}

// inside your button code
[SerializeField]
ButtonType _myType;
public ButtonType Type { get { return _myType; } }

EDIT:

Usage with Unity's event

// inside ButtonScript.Start() or ButtonScript.Awake()
this/* Button */.onClick.AddListener(new UnityEngine.Events.UnityAction(ButtonClicked));

// and now make a new method inside ButtonScript
void ButtonClicked()
{
    // method with tags:
    Debug.Log(gameObject.Tag == "YesButton" ? : "Yes" : "No");
    // method with enumeration:
    Debug.Log(_myType.ToString());
}

1 Comment

I've edited the answer to work with Unity's event system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.