命名 MonoBehaviour 类 GameManager 时的特殊图标 [英] Special Icon when naming a MonoBehaviour class GameManager

查看:42
本文介绍了命名 MonoBehaviour 类 GameManager 时的特殊图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Unity 中的GameManager 名称是否有什么特别之处,导致设计者采取不同的行动?我有一个名为 GameManager 的类,它是从 ScriptableObject 派生的,设计者对该类做了一些与我的其他 ScriptableObject 派生不同的事情类.

Is there something special about the name GameManager in Unity that causes the designer to act differently? I have a class named GameManager that is derived from ScriptableObject, and the designer is doing a few things differently for that class versus my other ScriptableObject derived classes.

我可以通过将名称从 GameManager 更改为 Manager 来验证此行为,并且 Unity 编辑器的行为有所不同.

I can verify this behavior by changing the name from GameManager to Manager, and the Unity editor acts differently.

我对GameManager的定义如下:

[CreateAssetMenu(menuName = "Managers/GameManager")]
public class GameManager : ScriptableObject
{
  // ...
}

当我的 C# 类命名为 GameManager 时,项目视图如下所示.注意 Game Manager 旁边的不同图标.

Here's what the Project view looks like when my C# class is named GameManager. Notice the different icon next to Game Manager.

如果我删除该资产,将底层 C# 类名称更改为 Manager,然后再次创建该资产,则图标是普通图标,而不是齿轮.

If I delete that asset, change the underlying C# class name to Manager, and then create the asset again, the icon is the normal icon, rather than being the gear.

另一个更严重的问题是,如果我有一个游戏对象,其中包含一个 MonoBehaviour,它具有 GameManager 类型的属性,则 Unity 获胜当我单击检查器中字段旁边的小圆圈图标时,不会向我显示现有的 GameManager 资产.Unity 让我将 GameManager 资产从项目视图拖到该字段中,但 Unity 不允许我通过单击该字段来选择引用.如下面的屏幕截图所示,Unity 没有给我选择我的 GameManager 资产的选项,即使它在项目视图中可用.

The other issue, which is more of a problem, is that if I have a game object that includes a MonoBehaviour that has a property of type GameManager, Unity won't show me the existing GameManager asset when I click on the little circle icon next to the field in the Inspector. Unity will let me drag the GameManager asset from the Project view into the field, but Unity won't let me select the reference by clicking in the field. As shown in the screenshots below, Unity doesn't give me the option of selecting my GameManager asset, even though it's available in the Project view.

但是,如果我将底层 C# 类的名称从 GameManager 更改为 Manager,Unity 编辑器将正常工作,如下所示.

However, If I change the name of the underlying C# class from GameManager to Manager, the Unity editor works correctly, as shown below.

GameManager 的 C# 类名是否有什么特别之处,或者这种行为可能是由于其他原因造成的?

Is there something special about the C# class name of GameManager, or could this behavior be due to something else?

推荐答案

Unity 中有一些特殊的脚本名称.当您使用其中任何一个时,特殊图标将应用于该脚本.GameManager 是特殊的脚本名称之一.Search 也是 Unity 中另一个特殊的脚本名称.不幸的是,它们并未在 Unity 网站的某处列出,但您绝对会知道何时使用了特殊脚本名称之一.

There are special scripts names in Unity. When you use any of those, special icon is applied to that script. GameManager is one of the special script names. Search is also another special script name in Unity. Unfortunately, they are not listed somewhere on Unity's website but you will absolutely know when you are using one of the special script names.

如果您仍想使用这些特殊名称来命名您的脚本,并且还想删除特殊图标或行为,请将带有特殊名称的脚本括在命名空间中.

If you still want to use those special names to name your script and also want to remove the special icons or behavior, enclose that script with the special name in a namespace.

namespace Ben
{
    public class Search : MonoBehaviour
    {

    }
}

Search 脚本的特殊图标现在应该消失了.这也适用于 GameManager 脚本.

The special icon for the Search script should now be gone. This also applies to the GameManager script.

编辑:

由于人们想了解更多,基本上,Unity 有这些包含其图标的重要文件:

Since people want to know more about this, basically, Unity has these important files that contains its icons:

  • unity 默认资源
  • Unity 编辑器资源
  • unity_builtin_extra

EditorDataResources 目录中.如果您将这些文件复制到您的 AssetsResources 目录并将其中三个文件的扩展名更改为 .asset,您将能够看到资产当您展开这些文件时,这些文件中的图标和图标.

in the <UnityInstallationDirecory>EditorDataResources directory. If you copy these files to your <ProjectDirecory>AssetsResources directory and change the files extension of three of them to .asset, you will be able to see assets and icon in those files when you expand them.

找到特殊图标的秘诀在于,任何名称以 "Icon" 结尾的图标都可能是特殊图标.例如,GameManager 有一个名为 GameManager Icon 的图标.将您的脚本命名为 GameManager 将使其使用 GameManager Icon.这并不完全适用于所有图标,而是大多数.很少有人不这样做.

The secret to finding the special icons is that any of those icons that has a named that ends with " Icon" is likely a special icon. For example, GameManager has an icon named GameManager Icon. Naming your script GameManager will make it use the GameManager Icon. This is not entirely true for all icon but most of them. Few don't do this.

我制作了一个脚本来在编辑器中自动执行上述指令.它适用于 Unity 2017,但在 Unity 2018 中似乎存在问题,我没有时间修复它.它在执行时在 Unity 2018 中显示许多错误,但之后它仍然可以正常工作.

I made a script to automate the instruction above in the Editor. It works in Unity 2017 but there seems to be issues with it in Unity 2018 and I haven't gotten some time to fix it. It shows many error in Unity 2018 when executed but it still works fine after that.

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


/*
Detects possible special script names
By Programmer
https://stackoverflow.com/users/3785314/programmer
*/

public class SpecialIconLister : MonoBehaviour
{
    [MenuItem("Programmer/Show Special Icons")]
    static void MainProc()
    {
        if (EditorUtility.DisplayDialog("Log and copy special Icon names?",
               "Are you sure you want to log and copy spacial icons to the clipboard?",
               "Yes", "Cancel"))
        {

            if (IsPlayingInEditor())
                return;

            //"unity default resources" contains models, materials an shaders
            //"unity editor resources" contains most icons lile GameManager Search and so on 
            //"unity_builtin_extra" contains UI images and Shaders

            //Files to copy to the Resources folder in the project
            string file1 = UnityEditorResourcesFilePath("unity default resources");
            string file2 = UnityEditorResourcesFilePath("unity editor resources");
            string file3 = UnityEditorResourcesFilePath("unity_builtin_extra");

            string dest1 = UnityProjectResourcesPath("unity default resources.asset");
            string dest2 = UnityProjectResourcesPath("unity editor resources.asset");
            string dest3 = UnityProjectResourcesPath("unity_builtin_extra.asset");

            //Create the Resources folder in the Project folder if it doesn't exist
            VerifyResourcesFolder(dest1);
            VerifyResourcesFolder(dest2);
            VerifyResourcesFolder(dest3);

            //Copy each file to the resouces folder
            if (!File.Exists(dest1))
                FileUtil.CopyFileOrDirectoryFollowSymlinks(file1, dest1);
            if (!File.Exists(dest2))
                FileUtil.CopyFileOrDirectoryFollowSymlinks(file2, dest2);
            if (!File.Exists(dest3))
                FileUtil.CopyFileOrDirectoryFollowSymlinks(file3, dest3);

            Debug.unityLogger.logEnabled = false;

            //Refresh Editor
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            //Load every object in that folder
            Resources.LoadAll("");

            //List the special icons
            GetSpecialIcons();

            CleanUp(dest1);
            CleanUp(dest2);
            CleanUp(dest3);

            //Refresh Editor
            AssetDatabase.Refresh();
            Resources.UnloadUnusedAssets();
            AssetDatabase.Refresh();
            Debug.unityLogger.logEnabled = false;
        }
    }

    static void SelectAsset(string resourcesFilePath)
    {
        UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath(resourcesFilePath, typeof(UnityEngine.Object));
        Selection.activeObject = obj;
    }

    static string AsoluteToRelative(string absolutePath)
    {
        string relativePath = null;
        if (absolutePath.StartsWith(Application.dataPath))
        {
            relativePath = "Assets" + absolutePath.Substring(Application.dataPath.Length);
        }
        return relativePath;
    }

    static void GetSpecialIcons()
    {
        //Get All Editor icons 
        List<UnityEngine.Object> allIcons;
        allIcons = new List<UnityEngine.Object>(Resources.FindObjectsOfTypeAll(typeof(Texture)));
        allIcons = allIcons.OrderBy(a => a.name, StringComparer.OrdinalIgnoreCase).ToList();


        //Get special icons from the icons
        List<string> specialIconsList = new List<string>();
        string suffix = " Icon";
        foreach (UnityEngine.Object icList in allIcons)
        {
            if (!IsEditorBuiltinIcon(icList))
                continue;

            //Check if icon name ends with the special suffix
            if (icList.name.EndsWith(suffix))
            {
                //Remove suffix from the icon name then add it to the special icons List if it doesn't exist yet
                string sIcon = icList.name.Substring(0, icList.name.LastIndexOf(suffix));
                if (!specialIconsList.Contains(sIcon))
                    specialIconsList.Add(sIcon);
            }
        }
        //Sort special icons from the icons
        specialIconsList = specialIconsList.OrderBy(a => a, StringComparer.OrdinalIgnoreCase).ToList();

        Debug.unityLogger.logEnabled = true;
        Debug.Log("Total # Icons found: " + allIcons.Count);
        Debug.Log("Special # Icons found: " + specialIconsList.Count);

        //Add new line after each icon for easy display or copying
        string specialIcon = string.Join(Environment.NewLine, specialIconsList.ToArray());
        Debug.Log(specialIcon);

        //Copy the special icon names to the clipboard
        GUIUtility.systemCopyBuffer = specialIcon;

        Debug.LogWarning("Special Icon names copied to cilpboard");
        Debug.LogWarning("Hold Ctrl+V to paste on any Editor");
    }

    static string UnityEditorResourcesFilePath(string fileName = null)
    {
        //C:/Program Files/Unity/Editor/Unity.exe
        string tempPath = EditorApplication.applicationPath;
        //C:/Program Files/Unity/Editor
        tempPath = Path.GetDirectoryName(tempPath);
        tempPath = Path.Combine(tempPath, "Data");
        tempPath = Path.Combine(tempPath, "Resources");
        //C:Program FilesUnityEditorDataResources
        if (fileName != null)
            tempPath = Path.Combine(tempPath, fileName);
        return tempPath;
    }

    static string UnityProjectResourcesPath(string fileName = null)
    {
        string tempPath = Application.dataPath;
        tempPath = Path.Combine(tempPath, "Resources");
        if (fileName != null)
            tempPath = Path.Combine(tempPath, fileName);
        return tempPath;
    }

    static bool IsEditorBuiltinIcon(UnityEngine.Object icon)
    {
        if (!EditorUtility.IsPersistent(icon))
            return false;

        return true;
    }

    static void VerifyResourcesFolder(string resourcesPath)
    {
        //Create Directory if it does not exist
        if (!Directory.Exists(Path.GetDirectoryName(resourcesPath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(resourcesPath));
        }
    }

    static bool IsPlayingInEditor()
    {
        return (Application.isPlaying && Application.isEditor);
    }

    static void CleanUp(string resourcesFilePath)
    {
        FileAttributes attr = File.GetAttributes(resourcesFilePath);
        if (!((attr & FileAttributes.Directory) == FileAttributes.Directory)
            && File.Exists(resourcesFilePath))
        {
            FileUtil.DeleteFileOrDirectory(resourcesFilePath);
        }
        System.GC.Collect();
    }

}

下面是当您转到 Programmer ---> Show Special Icons 菜单时复制到我的剪贴板的示例转储.它将显示所有可能的特殊字符.其中一些不是,但大多数是:

And below here is the Example dump copied to my clipboard when you go to the Programmer ---> Show Special Icons menu. It will show all the possible special characters. Some of them are not but most of them are:

AimConstraint
AnalyticsTracker
AnchorBehaviour
AnchorInputListenerBehaviour
Animation
AnimationClip
AnimationWindowEvent
Animator
AnimatorController
AnimatorOverrideController
AnimatorState
AnimatorStateMachine
AnimatorStateTransition
AnyStateNode
AreaEffector2D
AreaLight
AspectRatioFitter
Assembly
AssemblyDefinitionAsset
AssetStore
AudioChorusFilter
AudioClip
AudioDistortionFilter
AudioEchoFilter
AudioHighPassFilter
AudioListener
AudioLowPassFilter
AudioMixerController
AudioMixerGroup
AudioMixerSnapshot
AudioMixerView
AudioReverbFilter
AudioReverbZone
AudioSource
AudioSpatializerMicrosoft
Avatar
AvatarMask
BillboardAsset
BillboardRenderer
BlendTree
boo Script
BoxCollider
BoxCollider2D
BuoyancyEffector2D
Button
Camera
Canvas
CanvasGroup
CanvasRenderer
CanvasScaler
CapsuleCollider
CapsuleCollider2D
CGProgram
CharacterController
CharacterJoint
ChorusFilter
CircleCollider2D
Cloth
CloudRecoBehaviour
CollabChanges
CollabChangesConflict
CollabChangesDeleted
CollabConflict
CollabCreate
CollabDeleted
CollabEdit
CollabExclude
CollabMoved
CompositeCollider2D
ComputeShader
ConfigurableJoint
ConstantForce
ConstantForce2D
ContentPositioningBehaviour
ContentSizeFitter
cs Script
Cubemap
CylinderTargetBehaviour
DefaultAsset
DefaultSlate
DirectionalLight
DistanceJoint2D
dll Script
Dropdown
d_AimConstraint
d_AnchorBehaviour
d_AnchorInputListenerBehaviour
d_AspectRatioFitter
d_AudioMixerView
d_Canvas
d_CanvasGroup
d_CanvasRenderer
d_CanvasScaler
d_CloudRecoBehaviour
d_CollabChanges
d_CollabChangesConflict
d_CollabChangesDeleted
d_CollabConflict
d_CollabCreate
d_CollabDeleted
d_CollabEdit
d_CollabExclude
d_CollabMoved
d_ContentPositioningBehaviour
d_ContentSizeFitter
d_CylinderTargetBehaviour
d_EventSystem
d_EventTrigger
d_FreeformLayoutGroup
d_GraphicRaycaster
d_GridLayoutGroup
d_HorizontalLayoutGroup
d_ImageTargetBehaviour
d_LayoutElement
d_LightProbeProxyVolume
d_MidAirPositionerBehaviour
d_ModelTargetBehaviour
d_MultiTargetBehaviour
d_ObjectTargetBehaviour
d_ParentConstraint
d_ParticleSystem
d_PhysicalResolution
d_Physics2DRaycaster
d_PhysicsRaycaster
d_PlaneFinderBehaviour
d_PlayableDirector
d_PositionConstraint
d_RectTransform
d_RotationConstraint
d_ScaleConstraint
d_ScrollViewArea
d_SelectionList
d_SelectionListItem
d_SelectionListTemplate
d_SortingGroup
d_StandaloneInputModule
d_TimelineAsset
d_TouchInputModule
d_UserDefinedTargetBuildingBehaviour
d_VerticalLayoutGroup
d_VirtualButtonBehaviour
d_VuforiaBehaviour
d_VuMarkBehaviour
d_WireframeBehaviour
EchoFilter
EdgeCollider2D
EditorSettings
EventSystem
EventTrigger
Favorite
FixedJoint
FixedJoint2D
Flare
FlareLayer
Folder
FolderEmpty
FolderFavorite
Font
FreeformLayoutGroup
FrictionJoint2D
GameManager
GameObject
GraphicRaycaster
Grid
GridBrush
GridLayoutGroup
GUILayer
GUISkin
GUIText
GUITexture
Halo
HighPassFilter
HingeJoint
HingeJoint2D
HoloLensInputModule
HorizontalLayoutGroup
HumanTemplate
Image
ImageTargetBehaviour
InputField
Js Script
LayoutElement
LensFlare
Light
LightingDataAsset
LightingDataAssetParent
LightmapParameters
LightProbeGroup
LightProbeProxyVolume
LightProbes
LineRenderer
LODGroup
LowPassFilter
Mask
Material
Mesh
MeshCollider
MeshFilter
MeshParticleEmitter
MeshRenderer
MetaFile
Microphone
MidAirPositionerBehaviour
ModelTargetBehaviour
Motion
MovieTexture
MultiTargetBehaviour
MuscleClip
NavMeshAgent
NavMeshData
NavMeshObstacle
NetworkAnimator
NetworkDiscovery
NetworkIdentity
NetworkLobbyManager
NetworkLobbyPlayer
NetworkManager
NetworkManagerHUD
NetworkMigrationManager
NetworkProximityChecker
NetworkStartPosition
NetworkTransform
NetworkTransformChild
NetworkTransformVisualizer
NetworkView
ObjectTargetBehaviour
OcclusionArea
OcclusionPortal
OffMeshLink
Outline
ParentConstraint
ParticleAnimator
ParticleEmitter
ParticleRenderer
ParticleSystem
PhysicMaterial
Physics2DRaycaster
PhysicsMaterial2D
PhysicsRaycaster
PlaneFinderBehaviour
PlatformEffector2D
PlayableDirector
PointEffector2D
PolygonCollider2D
PositionAsUV1
PositionConstraint
Prefab
PrefabModel
PrefabNormal
Preset
ProceduralMaterial
Projector
RawImage
RaycastCollider
RectMask2D
RectTransform
ReflectionProbe
RelativeJoint2D
RenderTexture
ReverbFilter
Rigidbody
Rigidbody2D
RotationConstraint
ScaleConstraint
SceneAsset
SceneSet
ScriptableObject
Scrollbar
ScrollRect
Search
Selectable
Shader
ShaderVariantCollection
Shadow
SkinnedMeshRenderer
Skybox
Slider
SliderJoint2D
SoftlockProjectBrowser
SortingGroup
SpatialMappingCollider
SpatialMappingRenderer
SpeedTreeModel
SphereCollider
Spotlight
SpringJoint
SpringJoint2D
Sprite
SpriteAtlas
SpriteCollider
SpriteMask
SpriteRenderer
SpriteShapeRenderer
StandaloneInputModule
StyleSheet
SubstanceArchive
SurfaceEffector2D
TargetJoint2D
Terrain
TerrainCollider
TerrainData
Text
TextAsset
TextMesh
Texture
Texture2D
Tile
Tilemap
TilemapCollider2D
TilemapRenderer
TimelineAsset
Toggle
ToggleGroup
TouchInputModule
TrackedPoseDriver
TrailRenderer
Transform
UserDefinedTargetBuildingBehaviour
UssScript
UxmlScript
VerticalLayoutGroup
VideoClip
VideoEffect
VideoPlayer
VirtualButtonBehaviour
VisualTreeAsset
VuforiaBehaviour
VuMarkBehaviour
WheelCollider
WheelJoint2D
WindZone
WireframeBehaviour
WorldAnchor
WorldParticleCollider

这篇关于命名 MonoBehaviour 类 GameManager 时的特殊图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆