This is how you use it:
- Download the RequestParameters class.
- Add it to your project and attach it to a GameObject in your scene.
- Use PreviewLabs.RequestParameters.HasKey(string key) and PreviewLabs.RequestParameters.GetValue(string key) anywhere in your code to access URL parameters.
- Test it in the Editor by setting the test parameters string in the inspector window.
Some examples of what it could be used for:
- Creating a Unity Web Player e-card where you set the name of the recipient in the URL (this is the reason why I wrote the script; see holidaysCard.html?name=RequestParameters.cs%20User).
- Passing variables from one web player build to an other when using Application.OpenURL()
- Recognizing a user already logged in on your website.
This is the line of code doing the trick without requiring to modify the Web Player build’s HTML file each time a build is made:
Application.ExternalEval(
"UnityObject2.instances[0].getUnity().SendMessage('"
+ name + "',"
+ "'SetRequestParameters'"
+ ", document.location.search);");
How it works:
- From inside the RequestParameters.cs class, Application.ExternalEval() is used to execute JavaScript in the browser, from the context of the html page.
- Through the undocumented UnityObject2.instances[0], we get access to the Unity Web Player object, allowing us to send data from the JavaScript context back to the player (discovered on this question on Stackoverflow).
- SendMessage is used to pass the value of document.location.search (browser-side JavaScript code to get the part of the URL from the question mark).
- The document.location.search string is parsed and turned into a Dictionary, allowing easy and efficient retrieval of the parameters.
- WWW.UnEscapeURL() is used to convert from percent encoding used in URLs to normal strings (so space characters for instance are transformed from “%20” to a regular space).
The PreviewLabs.RequestParameters class is public domain, so you can use it any way you want to, modify it, use it in a commercial product, …
