GF源码笔记

资源加载成功的回调是一个怎样的运行流程?

举一个源码中的栗子,定位到Assets/GameFramework/Scripts/Runtime/Config/ConfigComponent.cs这个文件,在其Awake()方法中有下面一段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected override void Awake()
{
base.Awake();

m_ConfigManager = GameFrameworkEntry.GetModule<IConfigManager>();
if (m_ConfigManager == null)
{
Log.Fatal("Config manager is invalid.");
return;
}

m_ConfigManager.ReadDataSuccess += OnReadDataSuccess;
m_ConfigManager.ReadDataFailure += OnReadDataFailure;

if (m_EnableLoadConfigUpdateEvent)
{
m_ConfigManager.ReadDataUpdate += OnReadDataUpdate;
}

if (m_EnableLoadConfigDependencyAssetEvent)
{
m_ConfigManager.ReadDataDependencyAsset += OnReadDataDependencyAsset;
}
}

上面的代码片段中有四处使用委托:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <summary>
/// 读取数据成功事件。
/// </summary>
event EventHandler<ReadDataSuccessEventArgs> ReadDataSuccess;

/// <summary>
/// 读取数据失败事件。
/// </summary>
event EventHandler<ReadDataFailureEventArgs> ReadDataFailure;

/// <summary>
/// 读取数据更新事件。
/// </summary>
event EventHandler<ReadDataUpdateEventArgs> ReadDataUpdate;

/// <summary>
/// 读取数据时加载依赖资源事件。
/// </summary>
event EventHandler<ReadDataDependencyAssetEventArgs> ReadDataDependencyAsset;

具体实现类负责将委托进行注册,并在DataProvider<T>数据提供层负责在资源加载回调中,调用委托方法,从而实现在数据加载成功或者失败时所需要执行的操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private void LoadAssetSuccessCallback(string dataAssetName, object dataAsset, float duration, object userData)
{
try
{
if (!m_DataProviderHelper.ReadData(m_Owner, dataAssetName, dataAsset, userData))
{
throw new GameFrameworkException(Utility.Text.Format("Load data failure in data provider helper, data asset name '{0}'.", dataAssetName));
}

if (m_ReadDataSuccessEventHandler != null)
{
ReadDataSuccessEventArgs loadDataSuccessEventArgs = ReadDataSuccessEventArgs.Create(dataAssetName, duration, userData);
m_ReadDataSuccessEventHandler(this, loadDataSuccessEventArgs);
ReferencePool.Release(loadDataSuccessEventArgs);
}
}
catch (Exception exception)
{
if (m_ReadDataFailureEventHandler != null)
{
ReadDataFailureEventArgs loadDataFailureEventArgs = ReadDataFailureEventArgs.Create(dataAssetName, exception.ToString(), userData);
m_ReadDataFailureEventHandler(this, loadDataFailureEventArgs);
ReferencePool.Release(loadDataFailureEventArgs);
return;
}

throw;
}
finally
{
m_DataProviderHelper.ReleaseDataAsset(m_Owner, dataAsset);
}
}

UserData有何用?

其中有一个UserData,指的是用户自定义数据,在加载资源的时候,由用户通过参数传递,最后异步加载完在回调中把数据又带回来了。

加载资源的方式有哪些?

同步加载中,

异步加载中,分为远程服务器资源加载以及编辑器的本地加载两种

通过看源码,知道了编辑器加载模式中可以使用loadAssetInfo.DelaySeconds的方式模拟异步延迟加载的方式,