在Unity中使长名称更短?

代替编写类似的代码

public static String ecapse(String jsString) {
    jsString = jsString.replace("\\","\\\\");
    jsString = jsString.replace("\"","\\\"");
    jsString = jsString.replace("\b","\\b");
    jsString = jsString.replace("\f","\\f");
    jsString = jsString.replace("\n","\\n");
    jsString = jsString.replace("\r","\\r");
    jsString = jsString.replace("\t","\\t");
    jsString = jsString.replace("/","\\/");
    return jsString;
}

我只想输入

FindObjectOfType<GameManager>().gameOver()

在Unity中可以做到这一点吗?

也许使用某种别名,某种命名空间或其他名称。我将代码清理干净后,因此在使用GameManager的每个文件中使用GameManger gm = FindObjectOfType()并不是我想要的。

flypig1025 回答:在Unity中使长名称更短?

总的来说,我不鼓励这个问题。这是非常有问题的,我实际上不建议为类型(特别是对于完整的方法调用)不使用这种缩短的别名...当很多人使用变量和字段完成操作时,这已经够糟糕了。

始终使用正确的变量名和字段名,这样,通过阅读代码,您已经知道要处理的内容!


如何在开始时或需要时(但要尽早)将其存储在变量(或类字段)中

// You could also reference it already in the Inspector
// and skip the FindObjectOfType call entirely
[SerializeField] private _GameManager gm; 

private void Awake() 
{ 
    if(!gm) gm = FindObjectOfType<_GameManager>(); 
} 

,然后再使用

gm.gameOver();

需要的地方。

通常,您应该只执行一次,因为FindObjectOfType是一个非常注重性能的通话。

对于每个要使用_GameManager实例的类,当然必须这样做。

但是,大多数情况下这是首选的方式。


或者,您也可以(ab)使用 Singleton模式 ...这是有争议的,很多人都讨厌它...但是实际上在设计方面结束FindObjectOfType做同样的事情,并且性能甚至更差...

public class _GameManager : MonoBehaviour
{
    // Backing field where the instance reference will actually be stored
    private static _GameManager instance;

    // A public read-only property for either returning the existing reference
    // finding it in the scene
    // or creating one if not existing at all
    public static _GameManager Instance
    {
        get 
        {
            // if the reference exists already simply return it
            if(instance) return instance;

            // otherwise find it in the scene
            instance = FindObjectOfType<_GameManager>();

            // if found return it now
            if(instance) return instance;

            // otherwise a lazy creation of the object if not existing in scene
            instance = new GameObject("_GameManager").AddComponent<_GameManager>();

            return instance;
        }
    }

    private void Awake()
    {
        instance = this;
    }
}

所以您至少可以将其减少到

_GameManager.Instance.gameOver();

您现在可以创建的唯一别名是在文件顶部使用using语句,例如

using gm = _GameManager;

然后您就可以使用

gm.Instance.gameOver();

它可能不会比现在更短。

但是,正如前面所说,这是非常有问题的,并没有带来任何真正的好处,它只会使您的代码更难以阅读/维护!如果稍后您还拥有一个GridManager和一个GroupMaster怎么办?然后调用gm只会让人感到困惑;)


顺便说一句,您不应以_开头的类型。 MyGameManager或使用其他namespace来避免与现有类型发生名称冲突

本文链接:https://www.f2er.com/3168340.html

大家都在问