您可以使用 Firebase Remote Config 来定义应用中的参数并在云端更新它们的值。这样,您无需更新应用即可修改应用的外观和行为。
Remote Config 库用于存储应用内默认参数值,从 Remote Config 后端中提取更新后的参数值,以及控制提取的值何时可供应用使用。如需了解详情,请参阅 Remote Config 加载策略。
本指南逐步介绍了入门步骤并提供了一些示例代码,所有这些代码都可以从 firebase/quickstart-unity GitHub 代码库中克隆或下载。
将 Remote Config 添加至您的应用
在使用远程配置之前,您需要先完成以下步骤:
注册 Unity 项目并将其配置为使用 Firebase。
如果您的 Unity 项目已在使用 Firebase,那么您就已注册该 Unity 项目并已将其配置为使用 Firebase。
如果您没有 Unity 项目,则可以下载示例应用。
将 Firebase Unity SDK(具体而言是
FirebaseRemoteConfig.unitypackage
)添加到您的 Unity 项目中。
请注意,将 Firebase 添加到 Unity 项目需要在 Firebase 控制台中和打开的 Unity 项目中执行若干任务(例如,从控制台下载 Firebase 配置文件,然后将配置文件移动到 Unity 项目中)。
设置应用内默认参数值
您可以在远程配置对象中设置默认参数值,以便在后端中未检索到任何其他值时使用。这使得您的应用可以在连接到远程配置后端之前按预期运行。
为此,请创建一个字符串字典,并在其中填充表示您要添加的默认参数值的键值对。(调用 SetDefaults
时,非字符串属性将转化为该属性对应的类型。)
System.Collections.Generic.Dictionary<string, object> defaults = new System.Collections.Generic.Dictionary<string, object>(); // These are the values that are used if we haven't fetched data from the // server // yet, or if we ask for values that the server doesn't have: defaults.Add("config_test_string", "default local string"); defaults.Add("config_test_int", 1); defaults.Add("config_test_float", 1.0); defaults.Add("config_test_bool", false); Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.SetDefaultsAsync(defaults) .ContinueWithOnMainThread(task => {
获取要在应用中使用的参数值
现在,您可以从 Remote Config 对象中获取参数值。如果您已在 Remote Config 后端中设置值、提取然后激活它们,这些值便可供您的应用使用。否则,您将获得使用 SetDefaults() 配置的应用内参数值。
如需获取这些值,请使用 GetValue(),并以实参形式提供形参键。这将返回一个 ConfigValue,其中包含将值转换为各种基类型的属性。
在 Firebase 控制台中关联您的应用
在 Firebase 控制台中,将您的应用添加到 Firebase 项目中。
设置参数值
- 在 Firebase 控制台中,打开您的项目。
- 从菜单中选择 Remote Config 以查看 Remote Config 信息中心。
- 定义与您在应用中定义的参数同名的参数。对于每个参数,您可以设置默认值(最终将替换应用内默认值)和条件值。如需了解详情,请参阅远程配置参数和条件。
提取并激活值(根据需要)
如需从 Remote Config 后端提取参数值,请调用 FetchAsync()
方法。系统将提取您在后端中设置的所有值,并缓存在 Remote Config 对象中。
// Start a fetch request. // FetchAsync only fetches new data if the current data is older than the provided // timespan. Otherwise it assumes the data is "recent enough", and does nothing. // By default the timespan is 12 hours, and for production apps, this is a good // number. For this example though, it's set to a timespan of zero, so that // changes in the console will always show up immediately. public Task FetchDataAsync() { DebugLog("Fetching data..."); System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.DefaultInstance.FetchAsync( TimeSpan.Zero); return fetchTask.ContinueWithOnMainThread(FetchComplete); }
当提取操作完成后,通过 FetchAsync()
提取的值将缓存在本地,但直到调用 ActivateFetched()
之后才可使用。由于 FetchAsync()
是异步执行的,这可确保系统不会在计算过程中或在可能导致问题或奇怪行为的其他时间点应用新值。
(可选)启用开发者模式
如需启用开发者模式(可用于在开发过程中停用相关限制),您可以使用 FirebaseRemoteConfig.Setting
属性,设置一个新的 ConfigSettings
,并将 IsDeveloperMode
设置为 true。
后续步骤
浏览 Remote Config 用例并查看一些关键的概念和高级策略文档(如果您尚未这样做),包括: