Unity: Open Url on Button click

Published: 2020-04-15 16:03:02 -0400 -0400

Reading time: 1 mins (135 words)

Tags: 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://labs.iamhamy.xyz/projects/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.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus