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?
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.