using System.Collections; using System.Collections.Generic; using Fantasy; using Fantasy.Async; using Fantasy.ConfigTable; using Fantasy.Network; using UnityEngine; using UnityEngine.UI; using ErrorCode = UnityEditor.PackageManager.ErrorCode; public class Entry : MonoBehaviour { private Scene _scene; private Session _session; public Button GameInitCompleteButton; public Button StartCreateItemButton; public Button UseItemButton; public InputField UseItemId; void Start() { StartAsync().Coroutine(); } private async FTask StartAsync() { // 第一个参数,主要是为了兼容不容包管理器的路径 // Yoo、Addressable // 路径 + 包名字 = 完整的路径 // Assets/Bundles/Config + Config.bytes = Assets/Bundles/Config/Config.bytes ConfigTableHelper.Initialize("Assets/Bundles/Config", new AssetsBundleManager()); // 初始化框架 await Fantasy.Platform.Unity.Entry.Initialize(GetType().Assembly); // 创建一个Scene,这个Scene代表一个客户端的场景,客户端的所有逻辑都可以写这里 // 如果有自己的框架,也可以就单纯拿这个Scene做网络通讯也没问题。 _scene = await Scene.Create(SceneRuntimeType.MainThread); // 用当前的Scene创建一个新的网络连接 _session = _scene.Connect( "127.0.0.1:20000", NetworkProtocolType.KCP, OnConnectComplete, OnConnectFail, OnConnectDisconnect, false, 5000); var response = (G2C_LoginResponse)await _session.Call(new C2G_LoginRequest() { UserName = "Fantasy6666",PassWord = "666" }); if (response.ErrorCode != 0) { Log.Error($"登陆失败,错误码 = {response.ErrorCode}"); return; } Log.Debug("收到G2C_TestResponse UserName:\"Fantasy\""); GameInitCompleteButton.onClick.AddListener(() => OnGameInitCompleteButton().Coroutine()); StartCreateItemButton.onClick.AddListener(OnStartCreateItemButton); UseItemButton.onClick.AddListener(() => OnUseItemButton().Coroutine()); } private async FTask OnUseItemButton() { var itemId = long.Parse(UseItemId.text); var response = await _session.Call(new C2G_UseItemRequest() { ItemId = itemId, Count = 1, ContainerType = 1 }); if (response.ErrorCode != 0) { Log.Error($"无法使用物品 ErrorCode:{response.ErrorCode}"); } } private async FTask OnGameInitCompleteButton() { var response = await _session.Call(new C2G_GameInitCompleteRequest() { PushContainer = true }); if (response.ErrorCode != 0) { Log.Error($"无法跟服务器建立连接 ErrorCode:{response.ErrorCode}"); } } private void OnStartCreateItemButton() { _session.Send(new C2G_StartCreateItem()); } private void OnConnectComplete() { Log.Debug("OnConnectComplete"); _session.AddComponent().Start(ConstValue.Heartbeat); } private void OnConnectFail() { Log.Debug("OnConnectFail"); } private void OnConnectDisconnect() { Log.Debug("OnConnectDisconnect"); } }