Unity Remote Config 3.X правильно пишет сценарии для удаленных конфигурацийC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Unity Remote Config 3.X правильно пишет сценарии для удаленных конфигураций

Сообщение Anonymous »

Несколько дней назад я столкнулся с новой проблемой в моей игре в Unity, и эта проблема связана с Remote Config. В течение некоторого времени я хотел реализовать небольшую систему, в которой я хотел бы удаленно вносить некоторые изменения в ценности и некоторые вещи в моей игре. Теперь моя маленькая проблема заключается в следующем: в Интернете или на большинстве сайтов я вижу старую конфигурацию в скриптах с RemoteConfig (главная вещь (не знаю, как сказать) в скриптах с тем, что вы можете сделать скриптом и с чем вы можете установить соединение. между игрой и серверами Unity с онлайн-данными), а теперь и версии: 3.X для удаленной конфигурации. Структура файла совершенно другая (с разными сервисами), и я очень широко понимал, как это работает, но с моими попытками все в порядке-sh (хорошо, но, возможно, нет), но иногда у меня возникают ошибки в моих сценариях с этим компонентом Remote Config. И.Е. В моем скрипте есть предупреждения об аутентификации и основной службе.
Теперь ниже я разместил свой скрипт и образец Unity, чтобы увидеть ошибку, и хочу помочь мне с решением моей проблемы, чтобы создать хороший скрипт для моей игры. вносить изменения удаленно
P.S.: хочу сделать небольшую заметку. Я вошел в Unity со своей учетной записью, и соединение между Unity и серверами Unity в порядке, я думаю, потому что данные об онлайн-данных верны (строки и логические значения), а идентификатор среды совпадает с идентификатором среды на панели управления в браузере.
P.S. 2: У меня есть постоянное подключение к Интернету для всех тех же функций в Unity.
Помогите мне, пожалуйста.
Мой сценарий:
using System.Threading.Tasks;
using Unity.Services.RemoteConfig;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RemoteConfigGame : MonoBehaviour
{

public struct userAttributes { }
public struct appAttributes { }

public bool existUpdate;
public bool existMaintainance;
[SerializeField] GameManager gameManager;
[HideInInspector] string cloudVersion;

async Task InitializeRemoteConfigAsync()
{
// initialize handlers for unity game services
await UnityServices.InitializeAsync();

// remote config requires authentication for managing environment information
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
}

public void Awake()
{
RemoteConfigService.Instance.FetchCompleted += ApplyRemoteSettings;
RemoteConfigService.Instance.FetchConfigs(new userAttributes(), new appAttributes());
}

void ApplyRemoteSettings(ConfigResponse configResponse)
{

switch (configResponse.requestOrigin)
{
case ConfigOrigin.Default:
Debug.Log("Default values will be returned");
break;
case ConfigOrigin.Cached:
Debug.Log("Cached values loaded");
break;
case ConfigOrigin.Remote:
Debug.Log("Remote Values changed");
Debug.Log("RemoteConfigService.Instance.appConfig fetched: " + RemoteConfigService.Instance.appConfig.config.ToString());
break;
}
existMaintainance = RemoteSettings.GetBool("isMaintainance");
existUpdate = RemoteSettings.GetBool("isUpdate");
cloudVersion = RemoteSettings.GetString("publishVersion");

}

void Update()
{
if (existUpdate && !existMaintainance)
{
if (gameManager.wasUpdatePannel == false && gameManager.manuPannel.activeInHierarchy)
{
if ((cloudVersion != gameManager.versionString) && gameManager.wasLoaded == true)
{
gameManager.updatePannel.SetActive(true);
gameManager.manuPannel.SetActive(false);
gameManager.versionForUpToDate = cloudVersion;
}
}
else
{
gameManager.updatePannel.SetActive(false);
gameManager.manuPannel.SetActive(true);
}

}
else if ((existUpdate && existMaintainance) || (!existUpdate && existMaintainance) )
{
SceneManager.LoadScene("Maintainance");
}
}

void OnDestroy()
{
RemoteConfigService.Instance.FetchCompleted -= ApplyRemoteSettings;

}

}

Пример Unity:
// -----------------------------------------------------------------------------
//
// This sample example C# file can be used to quickly utilise usage of Remote Config APIs
// For more comprehensive code integration, visit https://docs.unity3d.com/Packages/com.u ... fig@latest
//
// -----------------------------------------------------------------------------

using System.Threading.Tasks;
using Unity.Services.RemoteConfig;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;

public class ExampleSample : MonoBehaviour
{

public struct userAttributes {}
public struct appAttributes {}

async Task InitializeRemoteConfigAsync()
{
// initialize handlers for unity game services
await UnityServices.InitializeAsync();

// options can be passed in the initializer, e.g if you want to set analytics-user-id use two lines from below:
// var options = new InitializationOptions().SetOption("com.unity.services.core.analytics-user-id", "my-user-id-123");
// await UnityServices.InitializeAsync(options);

// remote config requires authentication for managing environment information
if (!AuthenticationService.Instance.IsSignedIn)
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
}

async Task Start()
{
// initialize Unity's authentication and core services, however check for internet connection
// in order to fail gracefully without throwing exception if connection does not exist
if (Utilities.CheckForInternetConnection())
{
await InitializeRemoteConfigAsync();
}

RemoteConfigService.Instance.FetchCompleted += ApplyRemoteSettings;
RemoteConfigService.Instance.FetchConfigs(new userAttributes(), new appAttributes());

// -- Example on how to fetch configuration settings using filter attributes:
// var fAttributes = new filterAttributes();
// fAttributes.key = new string[] { "sword","cannon" };
// RemoteConfigService.Instance.FetchConfigs(new userAttributes(), new appAttributes(), fAttributes);

// -- Example on how to fetch configuration settings if you have dedicated configType:
// var configType = "specialConfigType";
// RemoteConfigService.Instance.FetchConfigs(configType, new userAttributes(), new appAttributes());
// -- Configuration can be fetched with both configType and fAttributes passed
// RemoteConfigService.Instance.FetchConfigs(configType, new userAttributes(), new appAttributes(), fAttributes);

// -- All examples from above will also work asynchronously, returning Task
// await RemoteConfigService.Instance.FetchConfigsAsync(new userAttributes(), new appAttributes());
// await RemoteConfigService.Instance.FetchConfigsAsync(new userAttributes(), new appAttributes(), fAttributes);
// await RemoteConfigService.Instance.FetchConfigsAsync(configType, new userAttributes(), new appAttributes());
// await RemoteConfigService.Instance.FetchConfigsAsync(configType, new userAttributes(), new appAttributes(), fAttributes);
}

void ApplyRemoteSettings(ConfigResponse configResponse)
{

switch (configResponse.requestOrigin)
{
case ConfigOrigin.Default:
Debug.Log("Default values will be returned");
break;
case ConfigOrigin.Cached:
Debug.Log("Cached values loaded");
break;
case ConfigOrigin.Remote:
Debug.Log("Remote Values changed");
Debug.Log("RemoteConfigService.Instance.appConfig fetched: " + RemoteConfigService.Instance.appConfig.config.ToString());
break;
}

}

}

В моем коде есть 2 предупреждения, и я хочу их исправить
Core Service not initialized.
Request might result in empty or incomplete response
Please refer to https://docs.unity3d.com/Packages/com.u ... ation.html

и
Auth Service not initialized.
Request might result in empty or incomplete response
Please refer to https://docs.unity3d.com/Packages/com.u ... ation.html



Подробнее здесь: https://stackoverflow.com/questions/751 ... ly-configs
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»