2023/06/18
建立连网请求功能测试 Unity专案
接下来实作连网功能测试
先创建一个测试连线的版本
开啓 Unity Hub使用 Unity 2021.3.7f1 开一个新专案建立 一般 UI 或 GUI 择一即可,测试建议使用GUI较方便- 使用一般 UI
滑鼠右键 "Hierachy" > "UI" > "Canvas" (Create Canvas)滑鼠左键 点Canvas in "Hierachy"> "Inspector" > "Canvas Scaler">"UI Scale Mode" Change to "Scale With Screen Size">
"Reference Resolution" Set to X"1920" Y"1080"滑鼠左键 点Canvas in "Hierachy"(Select "Canvas")>
滑鼠右键 "Canvas">"UI">"Legacy">"Text"(Create Text)>"txt_Result"(Name it)滑鼠左键 点Project>Asset>滑鼠右键"Create">"Folder">"Scripts"(Name it)左键双击"Scripts"Folder>滑鼠右键"Create"> C# Script>Type "GetTest"(得到 GetTest.cs)左键双击GetTest.cs打开IDE(Visual Studio)
以下是 GetTest.cs 的代码:
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" 意味着成功连网.
使用 GUI
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专案。