Unity 如何执行它的方法? [英] How does Unity execute its methods?

查看:18
本文介绍了Unity 如何执行它的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Unity3D 方面只有一点经验,但我注意到从 MonoBehaviour 派生的类可能包含具有预定义签名的函数,这些函数将以特殊方式调用.例如,如果我写:

I only have a small experience in Unity3D, but I noticed that classes that derive from MonoBehaviour may contain functions with predefined signatures that will be called in a special way. For instance, if I write:

void Update()
{
  //some code
}

这个方法会在每一帧被调用.

this method will be called every frame.

我想象在 Unity 内部有某种无限循环,它在每一帧为场景中的每个对象调用 Update 方法.但是它怎么知道对象实际上提供了 Update 方法实现呢?如果 Update 是对 MonoBehaviour 类中方法的覆盖,那将会很清楚,但是从语法判断(以及您可以通过任何访问权限实现此类方法的事实)修饰符)不是.那里有什么反射魔法吗?

I imagine that inside Unity there is some sort of an endless loop that calls the Update method every frame for each object on the scene. But how does it know that the object actually provides the Update method implementation? It would have been clear if Update was an override for a method in the MonoBehaviour class, but judging by the syntax (and the fact that you can implement such methods with any access modifier) it's not. Is there some reflection magic happening there?

推荐答案

http://blogs.unity3d.com/2015/12/23/1k-update-calls/

不,Unity 不会每次都使用 System.Reflection 来寻找魔法方法是时候打电话了.

No, Unity doesn’t use System.Reflection to find a magic method every time it needs to call one.

相反,第一次访问给定类型的 MonoBehaviour通过脚本运行时检查底层脚本(或者Mono 或 IL2CPP) 是否定义了任何魔术方法以及此信息被缓存.如果 MonoBehaviour 有一个特定的方法,它是添加到适当的列表中,例如,如果脚本具有 Update 方法定义它被添加到需要更新的脚本列表中每一帧.

Instead, the first time a MonoBehaviour of a given type is accessed the underlying script is inspected through scripting runtime (either Mono or IL2CPP) whether it has any magic methods defined and this information is cached. If a MonoBehaviour has a specific method it is added to a proper list, for example if a script has Update method defined it is added to a list of scripts which need to be updated every frame.

在游戏过程中 Unity 只是遍历这些列表并执行方法——就这么简单.此外,这就是为什么不重要的原因您的 Update 方法是公开的或私有的.

During the game Unity just iterates through these lists and executes methods from it — that simple. Also, this is why it doesn’t matter if your Update method is public or private.

这篇关于Unity 如何执行它的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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