This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
- 📢 welcome to like 👍 collect ⭐ message 📝 if there is an error please correct!
- 📢 This article was originally written by dumb code Y at 🙉
- 📢 The future is long and worth striving for a better life ✨
📢 preface
- Recently I am developing an application, and there is a need to connect to the external web page 🙈 through Unity
- I looked up ideas on the Internet, so I wrote a blog to learn how Unity can access the URL🙉
- Then come to learn and introduce ~🙊
🎄 connects Web pages using urls in Unity
There are several ways to access the URL on the web, so let’s take a look at the renderings
1. Use a link to connect directly
Write this connection method when you need to connect, such as the following write in Button click event, click can access Baidu. The same below
public void ConnectUrl()
{
Application.OpenURL("http://www.baidu.com");
}
Copy the code
2. Access the URL through WWW
You can see it on the InternetWWWAccess toURLI tried, butVSThe hints are already out of date, so let’s demonstrate
//WWW
var www = new WWW("file:///F:/anyun/zayFileWork/UnitySDK/WebView/Assets/Vuplex/WebView/Documentation/index.html");
Application.OpenURL(www.url);
Copy the code
3. Access the URL through UnityWebRequest
/ / the new UnityWebRequest
public void ConnectUrl1()
{
UnityWebRequest unityWebRequest = new UnityWebRequest("https://www.csdn.net/");
Application.OpenURL(unityWebRequest.url);
}
Copy the code
4. Access the URL through local HTML note that THE HTML here was loaded locally by me
// Use an absolute path
public void ConnectUrl1()
{
UnityWebRequest unityWebRequest = new UnityWebRequest("file:///F:/a/b/c/d/Assets/Vuplex/WebView/Documentation/index.html");
Application.OpenURL(unityWebRequest.url);
}
Copy the code
// Use relative paths
public void ConnectUrl2()
{
UnityWebRequest unityWebRequest = new UnityWebRequest(Application.dataPath + "/Resources/index.html");
Application.OpenURL(unityWebRequest.url);
}
Copy the code
(1)./ is the current directory (2).. / is the parent directory (3)/is the root directory
🔔 download files and images using urls
Let’s take a look at the demo. Here I have copied the downloaded Image directly to the Image in the scene
Download files from the URL
The local path of the storage must be added for the download of the file – name + suffix I am not named add suffix, only wrote a path, has been reporting error is also very depressed ah!
public IEnumerator DownFile()
{
// Download path
string url = "file://F:/a/b/private/Tex/%E5%9C%86%E8%84%B80.jpg";
// The local path of the storage
string localurl = Application.dataPath + "/Resources/bb.gif";
UnityWebRequest WebRequest = new UnityWebRequest(url);
DownloadHandlerFile Download = new DownloadHandlerFile(localurl);
WebRequest.downloadHandler = Download;
yield return WebRequest.SendWebRequest();
// Wait for the resource download to complete
while(! WebRequest.isDone) {yield return null;
}
if (string.IsNullOrEmpty(WebRequest.error))
{
// The file was downloaded successfully
Debug.Log("Download successful");
}
else
{
// File download failed
Debug.Log("Download failed"); }}Copy the code
The same goes for downloading an Image. You can use the GetSpriteByTexture method to convert the downloaded Image directly to the Image in your scene.
public IEnumerator DownTexture()
{
/* the external path of the package read in the android operating system must be prefixed with file:// the path must contain file name extensions */
string url = "file://F:/a/b/private/Tex/%E5%9C%86%E8%84%B80.jpg";
UnityWebRequest WebRequest = new UnityWebRequest(url);
DownloadHandlerTexture Download = new DownloadHandlerTexture(true);
WebRequest.downloadHandler = Download;
yield return WebRequest.SendWebRequest();
// Wait for the resource download to complete
while(! WebRequest.isDone) {yield return null;
}
if (string.IsNullOrEmpty(WebRequest.error))
{
// The file was downloaded successfully
// Read the image
Texture2D rexture = Download.texture;
texture2D.sprite = GetSpriteByTexture(rexture);
Debug.Log("Image downloaded successfully");
}
else
{
// File download failed
Debug.Log("Image download failed"); }}// Convert texture to image Sprite
Sprite GetSpriteByTexture(Texture2D tex)
{
Sprite _sprite = Sprite.Create(tex, new Rect(0.0, tex.width, tex.height), new Vector2(0.5 f.0.5 f));
return _sprite;
}
Copy the code
Same as reading files
public IEnumerator GetFile()
{
/* the external path of the package read in the android operating system must be prefixed with file:// the path must contain file name extensions */
string url = Application.dataPath + "/Resources/bb.gif";
UnityWebRequest WebRequest = new UnityWebRequest(url);
DownloadHandlerBuffer Download = new DownloadHandlerBuffer();
WebRequest.downloadHandler = Download;
yield return WebRequest.SendWebRequest();
// Wait for the resource download to complete
while(! WebRequest.isDone) {yield return null;
}
if (string.IsNullOrEmpty(WebRequest.error))
{
// File reading succeeded
// Read data
var data = Download.data;
Debug.Log("Success");
}
else
{
// Failed to read file
Debug.Log("Failure"); }}Copy the code
Post
public IEnumerator Post_Demo()
{
//Post the requested address
string url = "www.csdn.net";
// Parameters for the Post request
WWWForm form = new WWWForm();
form.AddField("key1"."value1");
form.AddField("key2"."value2");
UnityWebRequest webRequest = UnityWebRequest.Post(url, form);
// Send the request
yield return webRequest.SendWebRequest();
if (string.IsNullOrEmpty(webRequest.error))
{
// The request for Post was successful
// The return parameter of the Post request
var data = webRequest.downloadHandler.text;
Debug.Log(data);
Postttt.text = "Success";
}
else
{
// The Post request failed
Postttt.text = "Failure"; }}Copy the code
Get
public IEnumerator Get_Demo()
{
//Get the requested address
string url = "www.baidu.com";
UnityWebRequest webRequest = UnityWebRequest.Get(url);
// Send the request
yield return webRequest.SendWebRequest();
// Wait for the request to complete
while(! webRequest.isDone) {yield return null;
}
if (string.IsNullOrEmpty(webRequest.error))
{
// The request to Get succeeded
// Return parameters of the Get request
var data = webRequest.downloadHandler.text;
Debug.Log(data);
Getttt.text = "Success";
}
else
{
// The Get request failed
Getttt.text = "Failure"; }}Copy the code
🎁 encoding and decoding in Unity
Now that we’re talking about accessing and reading files, we’ll mention encoding and decoding
Some symbols in the URL cannot be parsed, so we need to encode them. For example: = the equal sign usually has special meaning. After encoding it, it will look like this, and there is no problem: %3d
In Unity System. Web. HttpUtility. UrlDecode cannot use, so we usually use code:
UnityWebRequest.EscapeURL(string url);
UnityWebRequest.EscapeURL(string url,Encoding e);
Copy the code
Decoding:
UnityWebRequest.UnEscapeURL(stringUrl); UnityWebRequest.UnEscapeURL(stringUrl Encoding e);Copy the code
The instance
string ccc = UnityWebRequest.UnEscapeURL("%e4%b8%ad%e5%9b%bd%e4%b8%96%e7%95%8c%e7%ac%ac%e4%b8%80%ef%bc%81", System.Text.Encoding.GetEncoding("utf-8"));// Convert url encoding to Chinese
Debug.Log(ccc);
string aaa = UnityWebRequest.EscapeURL("China is number one in the world!");// Chinese to URL encoding
Debug.Log(aaa);
Copy the code
💬 summary
Always thought that using Unity to access URL is difficult, the original learning just know the original so simple 😘
I don’t know if you quit school? 🥰