代码检查:若要在函数中使用 'GetSingleton' 调用的结果,'OnCreate' 必须包含 'RequireForUpdate' 调用。
当系统的 OnCreate 方法未通过 RequireForUpdate 请求 singleton 时,本检查会报告 ISystem 代码中的 SystemAPI.GetSingleton<T>() 和 GetSingletonEntity<T>() 调用。
如果没有 RequireForUpdate<T>() ,系统即使缺少 singleton 也能运行,这会导致 singleton 访问不安全。
示例
在此示例中,调用了 GetSingleton<GameConfig>() ,但系统尚未为更新请求 GameConfig。 快速修复会将缺少的要求添加到 OnCreate。
using Unity.Entities;
public partial struct ExampleSystem : ISystem
{
public void OnUpdate(ref SystemState state)
{
// Reported: singleton must be requested with RequireForUpdate
var config = SystemAPI.GetSingleton<GameConfig>();
}
}
using Unity.Entities;
public partial struct ExampleSystem : ISystem
{
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<GameConfig>();
}
public void OnUpdate(ref SystemState state)
{
var config = SystemAPI.GetSingleton<GameConfig>();
}
}
快速修复
使用快速修复为 singleton 类型添加缺少的 RequireForUpdate<T>() 调用,或一次性添加所有缺少的 singleton 要求。
如果没有 OnCreate 方法,快速修复会创建一个。 如果 OnCreate 已存在,会在其中插入缺少的请求。
2026年 5月 8日