Is there a simple way to display an error message?
There doesn't seem to be any simple way to display an error message to the user.
If I Debug.LogError(msg); and then Application.Quit(); the user thinks the program just suddenly crashed for no apparent reason? Lol.
Searching doesn't even show anyone else asking this question. I can't believe it's not a super common need? I guess I'll have to do some custom thing.
What do you all do about the need for this?
Answer by Hellium · Oct 02, 2021 at 09:05 PM
Yes, you'll need a custom solution.
Here is a simple and not recommended one (`OnGUI` should not be used for multiple reasons):
using UnityEngine;
public class ErrorPresenter : MonoBehaviour
{
private static ErrorPresenter _instance;
private string _message;
private static ErrorPresenter Instance
{
get
{
if(_instance == null)
{
_instance = new GameObject(nameof(ErrorPresenter)).AddComponent<ErrorPresenter>();
}
return _instance;
}
}
public static void Show(string message)
{
Instance._message = message;
}
private void OnGUI()
{
if(!string.IsNullOrWhiteSpace(_message))
{
Rect container = new Rect(Screen.width * 0.3f, Screen.height * 0.3f, Screen.width * 0.4f, Screen.height * 0.4f);
GUI.Box(container, (string) null);
GUILayout.BeginArea(new RectOffset(20, 20, 20, 20).Remove(container));
DrawLabel();
DrawButton();
GUILayout.EndArea();
}
}
private void DrawLabel()
{
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
GUILayout.Label(_message);
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
}
private static void DrawButton()
{
GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
if (GUILayout.Button("Quit", GUILayout.MaxWidth(Screen.width * 0.1f)))
#if UNITY_EDITOR
UnityEditor.EditorApplication.ExitPlaymode();
#else
Application.Quit();
#endif
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
}
And call ErrorPresenter.Show("My error message");
wherever and whenever you want.
I advise you building a simple canvas with Text & Buttons instead.
Thank you very much for your answer, which comes with a complete solution, if a bit outdated. I guess I'll build a canvas based solution, as you suggest, and post it here for posterity.
Your answer
Follow this Question
Related Questions
How i do i fix error cs1519 unexpected symbol ')' and '(' 2 Answers
Please help 0 Answers
because it appears I have to do? 1 Answer
code error 2 Answers
I got an error message when i downloaded The Blacksmith: Environments, HELP!! 2 Answers