Unity3D 未挂载脚本自动初始化

通过RuntimeInitializeOnLoadMethodAttribute属性,可以在游戏启动时自动执行没有挂载到GameObject上的脚本。
这样在做一些插件的时候会比较方便,不需要用户手动去添加脚本,只要启动游戏就能直接自动执行。

// Create a non-MonoBehaviour class which displays
// messages when a game is loaded.
using UnityEngine;

class MyClass
{
    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad()
    {
        new GameObject("Test");
    }

}

创建上面的代码,场景中不需要做任何操作。当点击运行的时候,场景里会自动出现一个名为Test的GameObject。

它还有下面四个参数

AfterSceneLoad	当场景加载完成后调用
BeforeSceneLoad	场景加载之前调用
AfterAssembliesLoaded	 当多有程序集加载完毕后,预加载资源初始化好之后回调。Callback when all assemblies are loaded and preloaded assets are initialized.
BeforeSplashScreen	Splash Screen显示之前调用。Immediately before the splash screen is shown.
SubsystemRegistration	子系统注册回调

示例

// Demonstration of RuntimeInitializeOnLoadMethod and the argument it can take.
using UnityEngine;

class MyClass
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void OnBeforeSceneLoadRuntimeMethod()
    {
        Debug.Log("第一个场景加载前");
    }

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    static void OnAfterSceneLoadRuntimeMethod()
    {
        Debug.Log("第一个场景加载后");
    }

    [RuntimeInitializeOnLoadMethod]
    static void OnRuntimeMethodLoad()
    {
        Debug.Log("第一个场景加载后");
    }
}

注意当有多个使用同一个参数的回调时,回调的顺序是不确定的。
在这里插入图片描述

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值