2023/06/18
先創建一個測試連線的版本
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class GetTest : MonoBehaviour
{
public Text text;
void Start()
{
StartCoroutine(GetTesting());
}
IEnumerator GetTesting()
{
UnityWebRequest webRequest = UnityWebRequest.Get("https://google.com");
yield return webRequest.SendWebRequest();
text.text = webRequest.downloadHandler.text;
}
}
9.滑鼠右鍵 "Hierachy" > "Create Empty" >
type "NetWorkManager"(得到名爲NetWorkManager的GameObject)
"Inspector">"Add Component">type"GetTest">附加GetTest.cs到"NetWorkManager"GameObject上>
拖曳"txt_Result"(txt_Result.text in "Hierachy")到"GetTest(Script)">Text > None(Text)>
綁定成功
10.按下播放鍵測試> 如果 txt_Result.text 顯示 "< !d octype html><html" 意味著成功連網.
3.建立名爲NetWorkManager的GameObject,附加GetTest.cs
以下是 GetTest.cs 的代碼:
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class GetTest : MonoBehaviour
{
private string downloadedText = "";
private Vector2 scrollPosition = Vector2.zero;
void Start()
{
StartCoroutine(GetTesting());
}
IEnumerator GetTesting()
{
UnityWebRequest webRequest = UnityWebRequest.Get("https://google.com");
yield return webRequest.SendWebRequest();
downloadedText = webRequest.downloadHandler.text;
}
private void OnGUI()
{
// Set the background box position and size
Rect backgroundRect = new Rect(Screen.width / 2 - 250,
Screen.height / 2 - 250, 500, 500);
// Draw the black background box
GUI.Box(backgroundRect, "", GUI.skin.box);
// Set the scroll view position and size
Rect scrollViewRect = new Rect(Screen.width / 2 - 240,
Screen.height / 2 - 240, 480, 480);
// Begin the scroll view
scrollPosition = GUI.BeginScrollView(scrollViewRect, scrollPosition,
new Rect(0, 0, 460, 1000));
// Draw the label with downloaded text
GUI.Label(new Rect(0, 0, 460, 1000), downloadedText);
// End the scroll view
GUI.EndScrollView();
}
}
4.按下播放鍵測試> 如果GUI顯示 "< !d octype html><html..." ,可滑動scrollbar看全文,意味著成功連網.
這樣就成功創建了一個測試連網請求功能的測試 Unity專案。