Unity: Open Url on Button click

Date: 2020-04-15 | unity | csharp |

problem

I want a button in my Unity app - coffeedash - to open a URL when a button is clicked. How can I tell Unity to switch over to a url? How can I set that as an action on button click?

solution

Basically we have two different things we're trying to accomplish:

  1. Add a button listener
  2. Create an action that causes a URL open

Here's a GameObject Monobehaviour that does both:

public class Example : Monobehaviour {
    public Button MyButton;

    void Awake() {
        MyButton.onClick.AddListener(OnMyButtonClick);
    }

    void OnMyButtonClick() {
        Application.OpenURL("https://hamy.xyz/labs/coffeedash");
    }
}

This example adds an onClick listener to our button (which means it will get called on button click), pointing it to the OnMyButtonClick function. Then we have the OnMyButtonClick function call Application.OpenURL which opens a browser to the url of your choice.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.