【发布时间】:2022-01-28 02:59:36
【问题描述】:
我是初学者,这是我在这里的第一篇文章,如果我能做得更好,请告诉我。
在 Unity 中使用 PUN 2,当用户尝试连接到 Photon 服务器但失败时,我尝试返回连接错误消息。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; //Library that provides utilities for scene management
using Photon.Pun; //Library for Photon, provides networking utilities
using Photon.Realtime; //Helps solve problems relating to matchmaking and fast communication
using UnityEngine.UI; //
public class MenuMan : MonoBehaviourPunCallbacks
{
public override void OnDisconnected(DisconnectCause cause) //Callback for when device fails to connect to server. Parameter 'cause' is the cause of this failure
{
Debug.Log("failed :("); // FOR DEBUGGING
Debug.Log(cause); //Prints in the console the cause of this connection failure
DisplayErrorMessage();
}
public Text Message;
public string MessageValue = " ";
public void DisplayErrorMessage() //Method that displays a connection error message to the user
{
SceneManager.LoadScene("Character Select Menu"); //Ensures user is on the Character Select menu
MessageValue = "AAAAAAA";
//Message.text = MessageValue;
Debug.Log(Message.text);
Debug.Log(MessageValue);
}
}
当我运行此代码时,文本“AAAAA”会闪烁一秒钟,然后消失。通过测试我发现这是由于某些原因首先显示的消息,并且只有在场景发生变化从而重置文本之后才会显示。
我尝试使用协程来延迟 MessageValue 的改变,直到场景改变:
public override void OnDisconnected(DisconnectCause cause) //Callback for when device fails to connect to server. Parameter 'cause' is the cause of this failure
{
StartCoroutine(GoToCSM());
DisplayErrorMessage();
}
IEnumerator GoToCSM()
{
Debug.Log("cor started");
SceneManager.LoadScene("Character Select Menu")
yield return new WaitForSeconds(3);
DisplayErrorMessage();
Debug.Log("Done");
}
public Text Message; //Initialises a 'Text' type object, which will be set to the Connection fail message
static string MessageValue = " "; //Initialises a string which will be written to the 'text' component of the above object
public void DisplayErrorMessage() //Method that displays a connection error message to the user
{
MessageValue = "AAAAAAA"; //Writes the string to be displayed to MessageValue
Message.text = MessageValue; //Sets the above text to the 'text' component of the Message object, thus displaying it on the screen
}
但是协程永远不会超过 yield 语句。它只是在 yield 语句处停止并且不会继续(甚至 Debug.Log("Done") 也没有被记录)。
但是当我尝试切换一些东西并将 SceneManager.LoadScene("Character Select Menu") 放在 yield 语句下方时,它执行得很好,以及下面的调试语句。我不知道为什么会这样,而且很困惑。
这本来是一个非常简单的 10 分钟任务,我浪费了好几天试图弄清楚现在该做什么。任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: c# visual-studio unity3d photon