【问题标题】:Unity Build error: The name 'EditorUtility' does not exist in the current contextUnity Build 错误:当前上下文中不存在名称“EditorUtility”
【发布时间】:2021-12-17 16:53:38
【问题描述】:

我有一个非常简单的问题。当我尝试统一构建游戏时出现构建错误。当我在编辑器中运行游戏时,它工作得很好。这是控制台中显示的错误。

Assets\Scripts\Pattern.cs(284,17): error CS0103: The name 'EditorUtility' does not exist in the current context

现在,这是错误引用的代码行:

EditorUtility.DisplayDialog("Great!", "You got the pattern right!", "Next Level!");

最后,如果你认为错误是我没有将正确的东西导入到脚本中,那么你就错了,因为我导入了这个:

using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEditor;

有人可以帮帮我吗?提前谢谢你。

编辑: 执行此代码:

#if UNITY_EDITOR
            EditorUtility.DisplayDialog("Meh", "You got the pattern wrong ):", "Try Again!");
#endif

不起作用。在构建版本中,它只是不显示消息框,它的行为就好像这一行只是一个注释。有人可以帮忙吗?

【问题讨论】:

  • 您不能在运行时代码中使用编辑器类。将脚本移动到编辑器文件夹。

标签: c# unity3d


【解决方案1】:

您现在出现错误的原因是,Unity 在编译时删除了“UnityEditor”命名空间,因为它们是为它设计的。这就是为什么当您尝试在平台上使用它时,“EditorUtility”将永远不会存在于除 UnityEditor 之外的任何平台上。因为“EditorUtility”在“UnityEditor”命名空间中。

因此,如果您想使用“EditorUtility”在 Unity 编辑器中执行相同的工作,您应该像他们一样自己实现它。

#if UNITY_EDITOR
    EditorUtility.DisplayDialog("Great!", "You got the pattern right!", "Next Level!");
#else
    YOUROWNCLASS.DisplayDialog("Great!", "You got the pattern right!", "Next Level!");
#endif

【讨论】:

  • other answer 不是早在两个小时前就已经回答了吗?
【解决方案2】:

UnityEditor 内容通常只能在编辑器中使用,因为在将游戏构建为独立 EXE 时无法使用它。

如果您实际上是为编辑器编译游戏,请尝试添加预处理器指令以包含与编辑器相关的内容。

#if UNITY_EDITOR
    EditorUtility.DisplayDialog("Great!", "You got the pattern right!", "Next Level!");
#endif

您还需要在 using UnityEditor; 行周围放置相同的 #if UNITY_EDITOR ... #endif 指令,正如 @Retired Ninja 在 cmets 中告诉我们的那样。

【讨论】:

  • 您确实需要将 ifdef 放在 using 周围。
  • 但我应该提一下:从那段文字的外观来看,这应该是一个面向玩家的对话? EditorUtility.DisplayDialog() 仅在您处于编辑器模式时才有效,因此对于实际玩游戏的任何人都没有用。您应该考虑使用 Unity UI 制作自己的对话框
  • 感谢@RetiredNinja!
  • @INTODAN 这正是预处理器指令的想法,它使得这些行在游戏过程中根本不会出现(除非你在编辑器中玩)。当你不在编辑器中时,你不能使用EditorUtility,你需要找到其他方式来显示对话框,很遗憾
  • @INTODAN 尽管这个答案是在另一个答案前 2 小时添加的,但您接受 other answer 而不是这个答案有什么特殊原因吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多