Bob*_*and -2 alias unity-game-engine
而不是编写像
FindObjectOfType<GameManager>().gameOver()
Run Code Online (Sandbox Code Playgroud)
我只想输入
gm.gameOver()
Run Code Online (Sandbox Code Playgroud)
有没有办法在Unity中做到这一点?
也许使用某种别名,或某种名称空间或其他名称。我将代码清理干净后,因此在寻找使用GameManager的每个文件中使用GameManger gm = FindObjectOfType()并不是我想要的。
总的来说,我不得不劝阻这个问题。这是非常有问题的,我实际上不建议对类型(尤其是对完整的方法调用)不使用这种缩短的别名...当很多人使用变量和字段完成操作时,这已经很糟糕了。
始终使用正确的变量名和字段名,这样,通过阅读代码,您已经知道要处理的内容!
如何在开始时或需要时(但尽早)将其存储在变量(或类字段)中
// 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>();
}
Run Code Online (Sandbox Code Playgroud)
然后再使用
gm.gameOver();
Run Code Online (Sandbox Code Playgroud)
在需要的地方。
通常,您应该只执行一次,因为这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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以你至少可以减少到
_GameManager.Instance.gameOver();
Run Code Online (Sandbox Code Playgroud)
您现在可以创建的唯一别名是使用using文件顶部的语句,例如
using gm = _GameManager;
Run Code Online (Sandbox Code Playgroud)
那么你可以使用
gm.Instance.gameOver();
Run Code Online (Sandbox Code Playgroud)
它可能不会比这短得多。
但是正如所说的那样,这是非常可疑的,并且没有带来任何真正的好处,它只会使您的代码更难以阅读/维护!如果稍后您GridManager又有和GroupMaster怎么办?然后调用某些东西gm只会令人困惑;)
顺便说一句,您不应以_。开头的类型,而应将其命名为例如,MyGameManager或者,namespace如果您想避免与现有类型发生名称冲突,请使用其他名称
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |