Note, there’s an update at the bottom of this answer
I’ve created this URLParameters singleton several years ago. Here’s a WebGL example of a Mandelbrot renderer where i used this script to parse the hash parameters which get automatically adjusted when you change the settings.
This script doesn’t need to be attached to a gameobject manually. Just register a callback like this in Start:
URLParameters.Instance.RegisterOnDone((url)=> {
Debug.Log("search parameters: " + url.Search);
Debug.Log("hash parameters: " + url.Hash);
});
This will automatically create an instance of the singleton which will send a javascript request to the browser which in turn will call a callback in that script which will trigger our callback. It also parses the search field as well as the hash / fragment into key-value-pairs in dictionaries. So you can do this in your callback:
string p = url.SearchParameters["myParameter"];
When you have an URL like this:
"https://my.domain.name/myPath.html?myParameter=Hello%20World"
“p” will contain "Hello World"
*** edit ***
Update
Since Unity is about to deprecate the ExternalEval API the original URLParameters may no longer work in the future. I’ve made a newer version of the URLParameters script which uses an embedded jslib file which should be auto-extracted into the plugins folder of your project on import.
Note that the new version works a bit different. Since we no longer have to use callbacks we can directly call those javascript extensions from C#. The script provides static properties which directly invoke a javascript method which immediately returns the current value from the JS world. The script doesn’t need to be attached to anything anymore. However you can still attach it to an object in your scene to provide test data for in-editor testing.
The new class comes with a couple of static properties to directly read the different parts of the current location in the browser:
- Protocol
- Hostname
- Port
- Pathname
- Search
- Hash
And those 3 mixed properties Host, Origin and Href. For more information read the comments in the file.
Additionally there’s two methods which split the search/query or the hash/fragment string into a dictionary for easy access. There are also two extension methods for a Dictionary<string,string>
(GetDouble, GetInt) which makes it very easy to directly parse numbers from such parameters
double d = URLParameters.GetSearchParameters().GetDouble("keyName", 42d);