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

查看:248
本文介绍了命名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时Project视图的外观.请注意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不允许我通过单击该字段来选择引用.如下面的屏幕快照所示,即使我的GameManager资产在项目"视图中可用,Unity也不给我选择的选项.

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.

关于C#类名GameManager是否有一些特殊之处,还是这种现象可能是由于其他原因引起的?

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 default resources
  • unity editor resources
  • unity_builtin_extra
  • unity default resources
  • unity editor resources
  • unity_builtin_extra

.如果将这些文件复制到您的<ProjectDirecory>\Assets\Resources目录中,并将其中三个文件的扩展名更改为.asset,则在展开这些文件时,您将能够看到这些文件中的资产和图标.

in the <UnityInstallationDirecory>\Editor\Data\Resources directory. If you copy these files to your <ProjectDirecory>\Assets\Resources 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 Files\Unity\Editor\Data\Resources
        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天全站免登陆