Here are the examples of the csharp api UnityEngine.Debug.LogError(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
892 Examples
19
Source : NativeShare.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public NativeShare AddFile( string filePath, string mime = null )
{
if( !string.IsNullOrEmpty( filePath ) && File.Exists( filePath ) )
{
files.Add( filePath );
mimes.Add( mime ?? string.Empty );
}
else
Debug.LogError( "File does not exist at path or permission denied: " + filePath );
return this;
}
19
Source : WebViewObject.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void Init(
Callback cb = null,
bool transparent = false,
string ua = "",
Callback err = null,
Callback httpErr = null,
Callback ld = null,
bool enableWKWebView = false,
Callback started = null,
Callback hooked = null
#if UNITY_EDITOR
, bool separated = false
#endif
)
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
_CWebViewPlugin_InitStatic(
Application.platform == RuntimePlatform.OSXEditor,
SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal);
#endif
onJS = cb;
onError = err;
onHttpError = httpErr;
onStarted = started;
onLoaded = ld;
onHooked = hooked;
#if UNITY_WEBGL
#if !UNITY_EDITOR
_gree_unity_webview_init(name);
#endif
#elif UNITY_WEBPLAYER
Application.ExternalCall("unityWebView.init", name);
#elif UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_LINUX
//TODO: UNSUPPORTED
Debug.LogError("Webview is not supported on this platform.");
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
{
var uri = new Uri(_CWebViewPlugin_GetAppPath());
var info = File.ReadAllText(uri.LocalPath + "Contents/Info.plist");
if (Regex.IsMatch(info, @"<key>CFBundleGetInfoString</key>\s*<string>Unity version [5-9]\.[3-9]")
&& !Regex.IsMatch(info, @"<key>NSAppTransportSecurity</key>\s*<dict>\s*<key>NSAllowsArbitraryLoads</key>\s*<true/>\s*</dict>")) {
Debug.LogWarning("<color=yellow>WebViewObject: NSAppTransportSecurity isn't configured to allow HTTP. If you need to allow any HTTP access, please shutdown Unity and invoke:</color>\n/usr/libexec/PlistBuddy -c \"Add NSAppTransportSecurity:NSAllowsArbitraryLoads bool true\" /Applications/Unity/Unity.app/Contents/Info.plist");
}
}
#if UNITY_EDITOR_OSX
// if (string.IsNullOrEmpty(ua)) {
// ua = @"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53";
// }
#endif
webView = _CWebViewPlugin_Init(
name,
transparent,
Screen.width,
Screen.height,
ua
#if UNITY_EDITOR
, separated
#else
, false
#endif
);
// define pseudo requestAnimationFrame.
EvaluateJS(@"(function() {
var vsync = 1000 / 60;
var t0 = window.performance.now();
window.requestAnimationFrame = function(callback, element) {
var t1 = window.performance.now();
var duration = t1 - t0;
var d = vsync - ((duration > vsync) ? duration % vsync : duration);
var id = window.setTimeout(function() {t0 = window.performance.now(); callback(t1 + d);}, d);
return id;
};
})()");
rect = new Rect(0, 0, Screen.width, Screen.height);
OnApplicationFocus(true);
#elif UNITY_IPHONE
webView = _CWebViewPlugin_Init(name, transparent, ua, enableWKWebView);
#elif UNITY_ANDROID
webView = new AndroidJavaObject("net.gree.unitywebview.CWebViewPlugin");
webView.Call("Init", name, transparent, ua);
#else
Debug.LogError("Webview is not supported on this platform.");
#endif
}
19
Source : AssetBundleBuilder.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
[Button]
public void PublishCatalog()
{
// Generate catalog
var catalog = new JObject();
foreach (var row in replacedetBundles)
{
var ab = new JObject {["version"] = row.Version};
catalog[row.Name] = ab;
}
File.WriteAllText($"replacedetBundles/{FolderName}/catalog.json", catalog.ToString());
Debug.Log($"Catalog generated for {buildTarget}");
// Generate retail catalog
var retailCatalog = new JObject();
foreach (var bundleName in BuiltInBundles)
{
if (catalog[bundleName] == null)
{
Debug.LogError($"Requested to built-in bundle {bundleName} which does not exist");
continue;
}
retailCatalog[bundleName] = catalog[bundleName];
}
Directory.CreateDirectory($"replacedets/Streamingreplacedets/{FolderName}/Bundles/");
File.WriteAllText($"replacedets/Streamingreplacedets/{FolderName}/Bundles/catalog.json", retailCatalog.ToString());
Debug.Log($"Stripped catalog generated for {buildTarget} and moved to Streamingreplacedets");
foreach (var bundle in BuiltInBundles)
{
File.Copy($"replacedetBundles/{FolderName}/" + bundle, $"replacedets/Streamingreplacedets/{FolderName}/Bundles/" + bundle,
true);
}
Debug.Log($"Completed publishing for target {buildTarget}");
}
19
Source : Game.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
protected virtual async void Start()
{
await UniTask.WaitUntil(() => Context.IsInitialized);
try
{
await Initialize();
}
catch (Exception e)
{
Debug.LogError(e);
// Not editor
if (Context.SelectedGameMode != GameMode.Unspecified)
{
Context.GameErrorState = new GameErrorState {Message = "DIALOG_LEVEL_LOAD_ERROR".Get(), Exception = e};
await UniTask.Delay(TimeSpan.FromSeconds(3));
var sceneLoader = new SceneLoader("Navigation");
sceneLoader.Load();
var transitioned = false;
Context.ScreenManager.ChangeScreen(OverlayScreen.Id, ScreenTransition.None, 0.4f, 1,
onFinished: screen => transitioned = true);
await UniTask.WaitUntil(() => transitioned && sceneLoader.IsLoaded);
sceneLoader.Activate();
}
}
}
19
Source : Game.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask Initialize(bool startAutomatically = true)
{
ObjectPool = new ObjectPool(this);
// Decide game mode
var mode = Context.SelectedGameMode;
if (mode == GameMode.Unspecified)
{
if (EditorGameMode != GameMode.Unspecified)
{
mode = EditorGameMode;
}
else
{
throw new Exception("Game mode not specified");
}
}
if (mode == GameMode.Tier)
{
var tierState = Context.TierState;
if (tierState == null)
{
await Context.LevelManager.LoadLevelsOfType(LevelType.Tier);
tierState = new TierState(MockData.Season.tiers[0]);
Context.TierState = tierState;
}
if (tierState.IsFailed || tierState.IsCompleted)
{
// Reset tier state
tierState = new TierState(tierState.Tier);
Context.TierState = tierState;
}
tierState.CurrentStageIndex++;
Level = tierState.Tier.Meta.stages[Context.TierState.CurrentStageIndex].ToLevel(LevelType.Tier);
Difficulty = Difficulty.Parse(Level.Meta.charts.Last().type);
}
else if (mode == GameMode.GlobalCalibration)
{
// Load global calibration level
Level = await Context.LevelManager.LoadOrInstallBuiltInLevel(BuiltInData.GlobalCalibrationModeLevelId,
LevelType.Temp);
Difficulty = Level.Meta.GetEasiestDifficulty();
// Initialize global calibrator
globalCalibrator = new GlobalCalibrator(this);
}
else
{
if (Context.SelectedLevel == null && Application.isEditor)
{
// Load test level
await Context.LevelManager.LoadFromMetadataFiles(LevelType.User, new List<string>
{
$"{Context.UserDataPath}/{EditorDefaultLevelDirectory}/level.json"
});
Context.SelectedLevel = Context.LevelManager.LoadedLocalLevels.Values.First();
Context.SelectedDifficulty = Context.SelectedLevel.Meta.GetHardestDifficulty();
}
Level = Context.SelectedLevel;
Difficulty = Context.SelectedDifficulty;
}
onGameReadyToLoad.Invoke(this);
await Resources.UnloadUnusedreplacedets();
// Load chart
print("Loading chart");
var chartMeta = Level.Meta.GetChartSection(Difficulty.Id);
var chartPath = "file://" + Level.Path + chartMeta.path;
string chartText;
using (var request = UnityWebRequest.Get(chartPath))
{
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
throw new Exception($"Failed to download chart from {chartPath}");
}
chartText = Encoding.UTF8.GetString(request.downloadHandler.data);
}
var mods = new HashSet<Mod>(Context.SelectedMods);
if (Application.isEditor && EditorForceAutoMod)
{
mods.Add(Mod.Auto);
}
if (mode == GameMode.GlobalCalibration)
{
mods.Clear();
}
Chart = new Chart(
chartText,
mods.Contains(Mod.FlipX) || mods.Contains(Mod.FlipAll),
mods.Contains(Mod.FlipY) || mods.Contains(Mod.FlipAll),
true,
Context.Player.Settings.UseExperimentalNoteAr,
mods.Contains(Mod.Fast) ? 1.5f : (mods.Contains(Mod.Slow) ? 0.75f : 1),
camera.orthographicSize
);
ChartLength = Chart.Model.note_list.Max(it => it.end_time);
foreach (var type in (NoteType[]) Enum.GetValues(typeof(NoteType)))
{
ObjectPool.UpdateNoteObjectCount(type, Chart.MaxSamePageNoteCountByType[type] * 3);
}
// Load audio
print("Loading audio");
AudioListener.pause = false;
if (Context.AudioManager == null) await UniTask.WaitUntil(() => Context.AudioManager != null);
Context.AudioManager.Initialize();
var audioPath = "file://" + Level.Path + Level.Meta.GetMusicPath(Difficulty.Id);
var loader = new AudioClipLoader(audioPath);
await loader.Load();
if (loader.Error != null)
{
Debug.LogError(loader.Error);
throw new Exception($"Failed to download audio from {audioPath}");
}
Music = Context.AudioManager.Load("Level", loader.AudioClip, false, false, true);
MusicLength = Music.Length;
// Load storyboard
string sbFile = null;
if (chartMeta.storyboard != null)
{
if (chartMeta.storyboard.localizations != null)
{
Debug.Log("Using localized storyboard");
sbFile = chartMeta.storyboard.localizations.GetOrDefault(Localization.Instance.SelectedLanguage.ToString());
if (sbFile == null)
{
Debug.LogError($"Localized storyboard for language {Localization.Instance.SelectedLanguage.ToString()} does not exist");
}
}
if (sbFile == null)
{
sbFile = chartMeta.storyboard.path;
}
}
if (sbFile == null)
{
sbFile = "storyboard.json";
}
StoryboardPath = Level.Path + sbFile;
if (File.Exists(StoryboardPath))
{
// Initialize storyboard
// TODO: Why File.ReadAllText() works but not UnityWebRequest?
// (UnityWebRequest downloaded text could not be parsed by Newtonsoft.Json)
try
{
var storyboardText = File.ReadAllText(StoryboardPath);
Storyboard = new Cytoid.Storyboard.Storyboard(this, storyboardText);
Storyboard.Parse();
await Storyboard.Initialize();
print($"Loaded storyboard from {StoryboardPath}");
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError("Could not load storyboard.");
}
}
// Load hit sound
if (Context.Player.Settings.HitSound != "none")
{
var resource = await Resources.LoadAsync<AudioClip>("Audio/HitSounds/" + Context.Player.Settings.HitSound);
Context.AudioManager.Load("HitSound", resource as AudioClip, isResource: true);
}
// State & config
State = new GameState(this, mode, mods);
Context.GameState = State;
if (Application.isEditor) Debug.Log("Chart checksum: " + State.ChartChecksum);
Config = new GameConfig(this);
// Touch handlers
if (mode != GameMode.GlobalCalibration && !State.Mods.Contains(Mod.Auto))
{
inputController.EnableInput();
}
// System config
Application.targetFrameRate = 120;
Context.SetAutoRotation(false);
// Update last played time
Level.Record.LastPlayedDate = DateTimeOffset.UtcNow;
Level.SaveRecord();
// Initialize note pool
ObjectPool.Initialize();
IsLoaded = true;
if (mode != GameMode.GlobalCalibration)
{
Context.ScreenManager.ChangeScreen(OverlayScreen.Id, ScreenTransition.None);
}
onGameLoaded.Invoke(this);
levelInfoParent.transform.RebuildLayout();
if (startAutomatically)
{
StartGame();
}
}
19
Source : ParallaxElement.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void SetGyroscopeMultiplier(float m)
{
GyroscopeMultiplier = m;
Debug.LogError(m);
}
19
Source : TransitionElement.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
protected async void Start()
{
if (!actOnOtherGameObjects && (rectTransform.gameObject != gameObject || canvasGroup.gameObject != gameObject))
{
Debug.LogError($"WARNING! TransitionElement {name} rectTransform and canvasGroup not set to self. (rectTransform: {rectTransform.gameObject.name}, canvasGroup: {canvasGroup.gameObject.name})");
}
}
19
Source : GamePreparationScreen.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
protected override void Render()
{
Context.SelectedLevel = Level;
if (PrintDebugMessages)
{
Debug.Log($"Id: {Level.Id}, Type: {Level.Type}");
Debug.Log($"IsLocal: {Level.IsLocal}, Path: {Level.Path}");
if (Level.OnlineLevel != null)
{
Debug.Log("OnlineLevel:");
Debug.Log(JsonConvert.SerializeObject(Level.OnlineLevel));
}
}
if (Context.IsOnline())
{
rankingsTab.UpdateRankings(Level.Id, Context.SelectedDifficulty.Id);
ratingTab.UpdateLevelRating(Level.Id);
var localVersion = Level.Meta.version;
Context.LevelManager.FetchLevelMeta(Level.Id, true).Then(it =>
{
LoadOwner();
print($"Remote version: {it.version}, local version: {localVersion}");
if (it.version > Level.Meta.version)
{
// Ask the user to update
Context.Haptic(HapticTypes.Warning, true);
var dialog = Dialog.Instantiate();
dialog.Message = "DIALOG_LEVEL_OUTDATED".Get();
dialog.UsePositiveButton = true;
dialog.UseNegativeButton = true;
dialog.OnPositiveButtonClicked = _ =>
{
DownloadAndUnpackLevel();
dialog.Close();
};
dialog.Open();
}
}).CatchRequestError(error =>
{
if (error.IsHttpError)
{
switch (error.StatusCode)
{
case 403:
case 404:
if (State == ScreenState.Active && !Level.IsLocal)
{
Dialog.PromptGoBack("DIALOG_COULD_NOT_ACCESS_LEVEL".Get());
}
return;
case 451:
if (State == ScreenState.Active && !Level.IsLocal)
{
Dialog.PromptGoBack("DIALOG_LEVEL_NO_LONGER_AVAILABLE".Get());
}
return;
}
}
Debug.LogError($"Could not fetch level {Level.Id} meta");
Debug.LogError(error);
});
}
LoadLevelPerformance();
LoadOwner();
UpdateTopMenu();
UpdateStartButton();
base.Render();
}
19
Source : PlayerPrefsExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static bool[] GetBoolArray(string key)
{
if (!PlayerPrefs.HasKey(key)) return new bool[0];
var bytes = Convert.FromBase64String(PlayerPrefs.GetString(key));
if (bytes.Length < 5)
{
Debug.LogError("Corrupt preference file for " + key);
return new bool[0];
}
if ((ArrayType) bytes[0] != ArrayType.Bool)
{
Debug.LogError(key + " is not a boolean array");
return new bool[0];
}
Initialize();
// Make a new bytes array that doesn't include the number of entries + identifier (first 5 bytes) and turn that into a BitArray
var bytes2 = new byte[bytes.Length - 5];
Array.Copy(bytes, 5, bytes2, 0, bytes2.Length);
var bits = new BitArray(bytes2) {Length = ConvertBytesToInt32(bytes)};
// Get the number of entries from the first 4 bytes after the identifier and resize the BitArray to that length, then convert it to a boolean array
var boolArray = new bool[bits.Count];
bits.CopyTo(boolArray, 0);
return boolArray;
}
19
Source : PlayerPrefsExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static string[] GetStringArray(string key)
{
if (PlayerPrefs.HasKey(key))
{
var completeString = PlayerPrefs.GetString(key);
var separatorIndex = completeString.IndexOf("|"[0]);
if (separatorIndex < 4)
{
Debug.LogError("Corrupt preference file for " + key);
return new string[0];
}
var bytes = Convert.FromBase64String(completeString.Substring(0, separatorIndex));
if ((ArrayType) bytes[0] != ArrayType.String)
{
Debug.LogError(key + " is not a string array");
return new string[0];
}
Initialize();
var numberOfEntries = bytes.Length - 1;
var stringArray = new string[numberOfEntries];
var stringIndex = separatorIndex + 1;
for (var i = 0; i < numberOfEntries; i++)
{
int stringLength = bytes[idx++];
if (stringIndex + stringLength > completeString.Length)
{
Debug.LogError("Corrupt preference file for " + key);
return new string[0];
}
stringArray[i] = completeString.Substring(stringIndex, stringLength);
stringIndex += stringLength;
}
return stringArray;
}
return new string[0];
}
19
Source : PlayerPrefsExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
private static void GetValue<T>(string key, T list, ArrayType arrayType, int vectorNumber,
Action<T, byte[]> convert) where T : IList
{
if (PlayerPrefs.HasKey(key))
{
var bytes = Convert.FromBase64String(PlayerPrefs.GetString(key));
if ((bytes.Length - 1) % (vectorNumber * 4) != 0)
{
Debug.LogError("Corrupt preference file for " + key);
return;
}
if ((ArrayType) bytes[0] != arrayType)
{
Debug.LogError(key + " is not a " + arrayType + " array");
return;
}
Initialize();
var end = (bytes.Length - 1) / (vectorNumber * 4);
for (var i = 0; i < end; i++)
{
convert(list, bytes);
}
}
}
19
Source : AssetMemory.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<T> Loadreplacedet<T>(string path, replacedetTag tag, CancellationToken cancellationToken = default,
replacedetOptions options = default, bool useFileCacheOnly = false) where T : Object
{
if (!taggedMemoryCache.ContainsKey(tag)) taggedMemoryCache[tag] = new SimplePriorityQueue<Entry>();
var suffix = "";
if (typeof(T) == typeof(Sprite))
{
if (options != default)
{
if (options is SpritereplacedetOptions spriteOptions)
{
suffix = $".{spriteOptions.FitCropSize[0]}.{spriteOptions.FitCropSize[1]}";
}
}
}
string variantPath;
if (!path.StartsWith("file://"))
{
variantPath = "file://" + GetCacheFilePath(path) + suffix;
}
else
{
variantPath = path + suffix;
}
var variantExists = File.Exists(variantPath.Substring("file://".Length));
var cachedreplacedet = GetCachedreplacedetEntry<T>(variantPath);
if (cachedreplacedet != null)
{
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Returning cached replacedet {variantPath}");
cachedreplacedet.Tags.Add(tag);
var taggedMemory = taggedMemoryCache[tag];
if (taggedMemory.Contains(cachedreplacedet))
{
taggedMemory.UpdatePriority(cachedreplacedet, queuePriority++);
}
else
{
taggedMemory.Enqueue(cachedreplacedet, queuePriority++);
}
return cachedreplacedet.replacedet;
}
// Currently loading
if (isLoading.Contains(path))
{
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Already loading {path}. Waiting...");
await UniTask.WaitUntil(() => !isLoading.Contains(path), cancellationToken: cancellationToken);
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Wait {path} complete.");
return await Loadreplacedet<T>(path, tag, cancellationToken, options);
}
CheckIfExceedTagLimit(tag);
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Started loading {path} with variant {suffix}.");
isLoading.Add(path);
var time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var loadPath = path;
// Cache remote
if (!path.StartsWith("file://"))
{
var cachePath = GetCacheFilePath(path);
if (!File.Exists(cachePath))
{
if (!useFileCacheOnly)
{
using (var request = UnityWebRequest.Get(path))
{
request.downloadHandler =
new DownloadHandlerFile(cachePath).Also(it => it.removeFileOnAbort = true);
await request.SendWebRequest();
if (cancellationToken != default && cancellationToken.IsCancellationRequested)
{
isLoading.Remove(path);
return default;
}
if (request.isNetworkError || request.isHttpError)
{
// TODO: Neo, fix your image CDN :)
if (request.responseCode != 422)
{
if (path.Contains("gravatar"))
{
Debug.LogWarning($"replacedetMemory: Failed to download {path}");
Debug.LogWarning(request.error);
}
else
{
Debug.LogError($"replacedetMemory: Failed to download {path}");
Debug.LogError(request.error);
}
}
isLoading.Remove(path);
return default;
}
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Saved {path} to {cachePath}");
}
}
else
{
isLoading.Remove(path);
return default;
}
}
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Cached at {cachePath}");
loadPath = "file://" + cachePath;
}
T replacedet = default;
if (typeof(T) == typeof(Sprite))
{
// Fit crop
loadPath = variantExists ? variantPath : loadPath;
using (var request = UnityWebRequest.Get(loadPath))
{
await request.SendWebRequest();
if (cancellationToken != default && cancellationToken.IsCancellationRequested)
{
isLoading.Remove(path);
return default;
}
if (request.isNetworkError || request.isHttpError)
{
// TODO: Neo, fix your image CDN :)
if (request.responseCode != 422)
{
Debug.LogError(
$"replacedetMemory: Failed to load {loadPath}");
Debug.LogError(request.error);
isLoading.Remove(path);
return default;
}
}
var bytes = request.downloadHandler.data;
if (bytes == null)
{
isLoading.Remove(path);
return default;
}
var texture = request.downloadHandler.data.ToTexture2D();
texture.name = variantPath;
// Fit crop
if (!variantExists && options != default)
{
if (!(options is SpritereplacedetOptions spriteOptions))
{
throw new ArgumentException();
}
if (texture.width != spriteOptions.FitCropSize[0] || texture.height != spriteOptions.FitCropSize[1])
{
var croppedTexture = TextureScaler.FitCrop(texture, spriteOptions.FitCropSize[0],
spriteOptions.FitCropSize[1]);
croppedTexture.name = variantPath;
Object.Destroy(texture);
texture = croppedTexture;
bytes = texture.EncodeToJPG();
var completed = false;
async void Task()
{
await UniTask.SwitchToThreadPool();
var cleanPath = variantPath.Substring("file://".Length);
Directory.CreateDirectory(Path.GetDirectoryName(cleanPath));
File.WriteAllBytes(cleanPath, bytes);
completed = true;
}
Task();
await UniTask.WaitUntil(() => completed);
}
else
{
var completed = false;
async void Task()
{
await UniTask.SwitchToThreadPool();
var cleanPath = variantPath.Substring("file://".Length);
Directory.CreateDirectory(Path.GetDirectoryName(cleanPath));
File.Copy(loadPath.Substring("file://".Length), cleanPath);
completed = true;
}
Task();
await UniTask.WaitUntil(() => completed);
}
}
var sprite = texture.CreateSprite();
memoryCache[variantPath] = new SpriteEntry(variantPath, tag, sprite);
replacedet = (T) Convert.ChangeType(sprite, typeof(T));
}
}
else if (typeof(T) == typeof(AudioClip))
{
var loader = new AudioClipLoader(variantPath);
await loader.Load();
if (cancellationToken != default && cancellationToken.IsCancellationRequested)
{
isLoading.Remove(path);
loader.Unload();
return default;
}
if (loader.Error != null)
{
isLoading.Remove(path);
Debug.LogError($"replacedetMemory: Failed to download audio from {variantPath}");
Debug.LogError(loader.Error);
return default;
}
var audioClip = loader.AudioClip;
memoryCache[variantPath] = new AudioEntry(variantPath, tag, loader);
replacedet = (T) Convert.ChangeType(audioClip, typeof(T));
}
taggedMemoryCache[tag].Enqueue(memoryCache[variantPath], queuePriority++);
time = DateTimeOffset.Now.ToUnixTimeMilliseconds() - time;
if (PrintDebugMessages) Debug.Log($"replacedetMemory: Loaded {variantPath} in {time}ms");
isLoading.Remove(path);
return replacedet;
}
19
Source : Run.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static Run After(float aDelay, System.Action aAction)
{
if (aDelay <= 0)
{
Debug.LogError("Run delay must be positive");
return null;
}
var tmp = new Run();
tmp.action = _RunAfter(tmp, aDelay, aAction);
tmp.Start();
return tmp;
}
19
Source : BundleManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void Release(string bundleId, bool force = false)
{
if (bundleId == null) throw new ArgumentNullException();
if (!LoadedBundles.ContainsKey(bundleId)) return;
var entry = LoadedBundles[bundleId];
entry.RefCount--;
if (entry.RefCount <= 0 || force)
{
if (entry.RefCount < 0)
{
Debug.LogError("RefCount < 0!");
}
entry.replacedetBundle.Unload(true);
LoadedBundles.Remove(bundleId);
}
}
19
Source : Context.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
private async void InitializeApplication()
{
if (Application.platform == RuntimePlatform.Android)
{
// Get Android version
using (var version = new AndroidJavaClreplaced("android.os.Build$VERSION")) {
AndroidVersionCode = version.GetStatic<int>("SDK_INT");
print("Android version code: " + AndroidVersionCode);
}
}
LunarConsole.SetConsoleEnabled(true); // Enable startup debug
InitializationState = new InitializationState();
UserDataPath = Application.persistentDataPath;
if (Application.platform == RuntimePlatform.Android)
{
var dir = GetAndroidStoragePath();
if (dir == null)
{
Application.Quit();
return;
}
UserDataPath = dir + "/Cytoid";
}
else if (Application.platform == RuntimePlatform.IPhonePlayer)
{
// iOS 13 fix
iOSTemporaryInboxPath = UserDataPath
.Replace("Doreplacedents/", "")
.Replace("Doreplacedents", "") + "/tmp/me.tigerhix.cytoid-Inbox/";
}
print("User data path: " + UserDataPath);
#if UNITY_EDITOR
Application.runInBackground = true;
#endif
if (SceneManager.GetActiveScene().name == "Navigation") StartupLogger.Instance.Initialize();
Debug.Log($"Package name: {Application.identifier}");
Application.lowMemory += OnLowMemory;
Application.targetFrameRate = 120;
Input.gyro.enabled = true;
DOTween.defaultEaseType = Ease.OutCubic;
UnityEngine.Screen.sleepTimeout = SleepTimeout.NeverSleep;
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new UnityColorConverter()
},
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
BsonMapper.Global.RegisterType
(
color => "#" + ColorUtility.ToHtmlStringRGB(color),
s => s.replacedtring.ToColor()
);
FontManager.LoadFonts();
if (Application.platform == RuntimePlatform.Android)
{
// Try to write to ensure we have write permissions
try
{
// Create an empty folder if it doesn't already exist
Directory.CreateDirectory(UserDataPath);
File.Create(UserDataPath + "/.nomedia").Dispose();
// Create and delete test file
var file = UserDataPath + "/" + Path.GetRandomFileName();
File.Create(file);
File.Delete(file);
}
catch (Exception e)
{
Debug.LogError(e);
Dialog.PromptUnclosable("DIALOG_CRITICAL_ERROR_COULD_NOT_START_GAME_REASON_X".Get(
"DIALOG_CRITICAL_ERROR_REASON_WRITE_PERMISSION".Get()));
return;
}
}
try
{
var timer = new BenchmarkTimer("LiteDB");
Database = CreateDatabase();
// Database.Checkpoint();
timer.Time();
}
catch (Exception e)
{
Debug.LogError(e);
Dialog.Instantiate().Also(it =>
{
it.UseNegativeButton = false;
it.UsePositiveButton = false;
it.Message =
"DIALOG_CRITICAL_ERROR_COULD_NOT_START_GAME_REASON_X".Get(
"DIALOG_CRITICAL_ERROR_REASON_DATABASE".Get());
}).Open();
return;
}
// LiteDB warm-up
Library.Initialize();
// Load settings
Player.Initialize();
// Initialize audio
var audioConfig = AudioSettings.GetConfiguration();
DefaultDspBufferSize = audioConfig.dspBufferSize;
if (Application.isEditor)
{
audioConfig.dspBufferSize = 2048;
}
else if (Application.platform == RuntimePlatform.Android && Player.Settings.AndroidDspBufferSize > 0)
{
audioConfig.dspBufferSize = Player.Settings.AndroidDspBufferSize;
}
AudioSettings.Reset(audioConfig);
await UniTask.WaitUntil(() => AudioManager != null);
AudioManager.Initialize();
InitialWidth = UnityEngine.Screen.width;
InitialHeight = UnityEngine.Screen.height;
UpdateGraphicsQuality();
SelectedMods = new HashSet<Mod>(Player.Settings.EnabledMods);
PreSceneChanged.AddListener(OnPreSceneChanged);
PostSceneChanged.AddListener(OnPostSceneChanged);
OnLanguageChanged.AddListener(FontManager.UpdateSceneTexts);
Localization.Instance.SelectLanguage((Language) Player.Settings.Language);
OnLanguageChanged.Invoke();
// TODO: Add standalone support?
#if UNITY_IOS || UNITY_ANDROID
await BundleManager.Initialize();
#endif
if (Player.ShouldOneShot(StringKey.FirstLaunch))
{
Player.SetTrigger(StringKey.FirstLaunch);
}
switch (SceneManager.GetActiveScene().name)
{
case "Navigation":
if (Player.ShouldTrigger(StringKey.FirstLaunch, false))
{
InitializationState.FirstLaunchPhase = FirstLaunchPhase.GlobalCalibration;
// Global calibration
SelectedGameMode = GameMode.GlobalCalibration;
var sceneLoader = new SceneLoader("Game");
await sceneLoader.Load();
sceneLoader.Activate();
}
else
{
await InitializeNavigation();
}
break;
case "Game":
break;
}
await UniTask.DelayFrame(0);
graphyManager = GraphyManager.Instance;
UpdateProfilerDisplay();
IsInitialized = true;
OnApplicationInitialized.Invoke();
LunarConsole.SetConsoleEnabled(Player.Settings.UseDeveloperConsole);
ShouldSnapshotDatabase = true;
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<List<string>> CopyBuiltInLevelsToDownloads(List<string> levelIds)
{
var packagePaths = new List<string>();
// Install all missing training levels that are built in
foreach (var uid in levelIds)
{
var packagePath = Application.streamingreplacedetsPath + "/Levels/" + uid + ".cytoidlevel";
if (Application.platform == RuntimePlatform.IPhonePlayer) packagePath = "file://" + packagePath;
// Copy the file from Streamingreplacedets to temp directory
using (var request = UnityWebRequest.Get(packagePath))
{
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
Debug.LogError($"Failed to copy level {uid} from Streamingreplacedets");
continue;
}
var bytes = request.downloadHandler.data;
var targetDirectory = $"{Application.temporaryCachePath}/Downloads";
var targetFile = $"{targetDirectory}/{uid}.cytoidlevel";
try
{
Directory.CreateDirectory(targetDirectory);
File.WriteAllBytes(targetFile, bytes);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to copy level {uid} from Streamingreplacedets to {targetFile}");
continue;
}
packagePaths.Add(targetFile);
}
}
return packagePaths;
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<List<string>> InstallUserCommunityLevels()
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
var files = new List<string>();
var inboxPath = Context.UserDataPath + "/Inbox/";
if (Directory.Exists(inboxPath))
{
files.AddRange(Directory.GetFiles(inboxPath, "*.cytoidlevel"));
files.AddRange(Directory.GetFiles(inboxPath, "*.cytoidlevel.zip"));
}
if (Directory.Exists(Context.iOSTemporaryInboxPath))
{
files.AddRange(Directory.GetFiles(Context.iOSTemporaryInboxPath, "*.cytoidlevel"));
files.AddRange(Directory.GetFiles(Context.iOSTemporaryInboxPath, "*.cytoidlevel.zip"));
}
foreach (var file in files)
{
if (file == null) continue;
var toPath = Context.UserDataPath + "/" + Path.GetFileName(file);
try
{
if (File.Exists(toPath))
{
File.Delete(toPath);
}
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to delete .cytoidlevel file at {toPath}");
continue;
}
try
{
File.Move(file, toPath);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Failed to move .cytoidlevel file from {file} to {toPath}");
}
}
}
var levelFiles = new List<string>();
try
{
levelFiles.AddRange(Directory.GetFiles(Context.UserDataPath, "*.cytoidlevel"));
levelFiles.AddRange(Directory.GetFiles(Context.UserDataPath, "*.cytoidlevel.zip"));
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError("Cannot read from data path");
return new List<string>();
}
return await InstallLevels(levelFiles, LevelType.User);
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<List<string>> InstallLevels(List<string> packagePaths, LevelType type)
{
var loadedLevelJsonFiles = new List<string>();
var index = 1;
foreach (var levelFile in packagePaths)
{
var fileName = Path.GetFileNameWithoutExtension(levelFile);
OnLevelInstallProgress.Invoke(fileName, index, packagePaths.Count);
var destFolder = $"{type.GetDataPath()}/{fileName}";
if (await UnpackLevelPackage(levelFile, destFolder))
{
loadedLevelJsonFiles.Add(destFolder + "/level.json");
Debug.Log($"Installed {index}/{packagePaths.Count}: {levelFile}");
}
else
{
Debug.LogWarning($"Could not install {index}/{packagePaths.Count}: {levelFile}");
}
try
{
File.Delete(levelFile);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Could not delete level file at {levelFile}");
}
index++;
}
return loadedLevelJsonFiles;
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<bool> UnpackLevelPackage(string packagePath, string destFolder)
{
const int bufferSize = 256 * 1024;
ZipStrings.CodePage = Encoding.UTF8.CodePage;
try
{
Directory.CreateDirectory(destFolder);
}
catch (Exception error)
{
Debug.LogError("Failed to create level folder.");
Debug.LogError(error);
return false;
}
string fileName;
try
{
fileName = Path.GetFileName(packagePath);
}
catch (Exception error)
{
Debug.LogError($"Failed to get filename for path {packagePath}.");
Debug.LogError(error);
return false;
}
byte[] zipFileData;
try
{
zipFileData = File.ReadAllBytes(packagePath);
}
catch (Exception error)
{
Debug.LogError($"Failed to read bytes from {packagePath}.");
Debug.LogError(error);
return false;
}
using (var fileStream = new MemoryStream())
{
ZipFile zipFile;
try
{
fileStream.Write(zipFileData, 0, zipFileData.Length);
fileStream.Flush();
fileStream.Seek(0, SeekOrigin.Begin);
zipFile = new ZipFile(fileStream);
foreach (ZipEntry entry in zipFile)
{
// Loop through all files to ensure the zip is valid
}
}
catch (Exception e)
{
Debug.LogError($"Cannot read {fileName}. Is it a valid .zip archive file?");
Debug.LogError(e.Message);
return false;
}
foreach (ZipEntry entry in zipFile)
{
var targetFile = Path.Combine(destFolder, entry.Name);
if (entry.Name.Contains("__MACOSX")) continue; // replaced macOS...
Debug.Log("Extracting " + entry.Name + "...");
try
{
var outputFile = File.Create(targetFile);
using (outputFile)
{
if (entry.Size <= 0) continue;
var zippedStream = zipFile.GetInputStream(entry);
var dataBuffer = new byte[bufferSize];
int readBytes;
while ((readBytes = await zippedStream.ReadAsync(dataBuffer, 0, bufferSize)) > 0)
{
outputFile.Write(dataBuffer, 0, readBytes);
outputFile.Flush();
}
}
}
catch (Exception e)
{
Debug.LogError($"Cannot extract {entry.Name} from {fileName}. Is it a valid .zip archive file?");
Debug.LogError(e.Message);
return false;
}
}
var info = new FileInfo(destFolder);
var path = info.FullName + Path.DirectorySeparatorChar;
Debug.Log($"Removing {path}");
loadedPaths.Remove(path);
var coverPath = path + CoverThumbnailFilename;
Debug.Log($"Search {coverPath}");
if (File.Exists(coverPath))
{
try
{
File.Delete(coverPath);
File.Delete(coverPath + ".288.180");
File.Delete(coverPath + ".432.270");
File.Delete(coverPath + ".576.360"); // TODO: Unhardcode this (how?)
}
catch (Exception e)
{
Debug.LogError($"Failed to delete cover thumbnail: {coverPath}");
Debug.LogError(e);
}
}
}
return true;
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void DownloadAndUnpackLevelDialog(
Level level,
bool allowAbort = true,
Action onDownloadSucceeded = default,
Action onDownloadAborted = default,
Action onDownloadFailed = default,
Action<Level> onUnpackSucceeded = default,
Action onUnpackFailed = default,
bool forceInternational = false,
bool batchDownloading = false,
int batchDownloadCurrent = default,
int batchDownloadTotal = default
)
{
if (!Context.OnlinePlayer.IsAuthenticated)
{
Toast.Next(Toast.Status.Failure, "TOAST_SIGN_IN_REQUIRED".Get());
return;
}
if (onDownloadSucceeded == default) onDownloadSucceeded = () => { };
if (onDownloadAborted == default) onDownloadAborted = () => { };
if (onDownloadFailed == default) onDownloadFailed = () => { };
if (onUnpackSucceeded == default) onUnpackSucceeded = _ => { };
if (onUnpackFailed == default) onUnpackFailed = () => { };
var dialog = Dialog.Instantiate();
dialog.Message = batchDownloading ? "DIALOG_BATCH_DOWNLOADING_P_Q".Get(batchDownloadCurrent, batchDownloadTotal) : "DIALOG_DOWNLOADING".Get();
dialog.UseProgress = true;
dialog.UsePositiveButton = false;
dialog.UseNegativeButton = allowAbort;
ulong downloadedSize;
var totalSize = 0UL;
var downloading = false;
var aborted = false;
var targetFile = $"{Application.temporaryCachePath}/Downloads/{level.Id}-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.cytoidlevel";
var destFolder = $"{level.Type.GetDataPath()}/{level.Id}";
try
{
Directory.CreateDirectory(destFolder);
}
catch (Exception error)
{
Debug.LogError("Failed to create level folder.");
Debug.LogError(error);
onDownloadFailed();
return;
}
if (level.IsLocal)
{
// Write to the local folder instead
destFolder = level.Path;
}
// Download detail first, then package
RequestHelper req;
var downloadHandler = new DownloadHandlerFile(targetFile)
{
removeFileOnAbort = true
};
RestClient.Get<OnlineLevel>(req = new RequestHelper
{
Uri = $"{(forceInternational ? CdnRegion.International.GetApiUrl() : Context.ApiUrl)}/levels/{level.Id}",
Headers = Context.OnlinePlayer.GetRequestHeaders(),
EnableDebug = true
}).Then(it =>
{
if (aborted)
{
throw new OperationCanceledException();
}
totalSize = (ulong) it.Size;
downloading = true;
var packagePath = (forceInternational ? CdnRegion.International : Context.CdnRegion).GetPackageUrl(level.Id);
Debug.Log($"Package path: {packagePath}");
// Get resources
return RestClient.Post<OnlineLevelResources>(req = new RequestHelper
{
Uri = packagePath,
Headers = Context.OnlinePlayer.GetRequestHeaders(),
BodyString = SecuredOperations.WithCaptcha(new { }).ToString(),
EnableDebug = true
});
}).Then(res =>
{
if (aborted)
{
throw new OperationCanceledException();
}
Debug.Log($"replacedet path: {res.package}");
// Start download
// TODO: Change to HttpClient
return RestClient.Get(req = new RequestHelper
{
Uri = res.package,
DownloadHandler = downloadHandler,
WillParseBody = false
});
}).Then(async res =>
{
downloading = false;
try
{
onDownloadSucceeded();
}
catch (Exception e)
{
Debug.LogError(e);
}
dialog.OnNegativeButtonClicked = it => { };
dialog.UseNegativeButton = false;
dialog.Progress = 0;
dialog.Message = "DIALOG_UNPACKING".Get();
DOTween.To(() => dialog.Progress, value => dialog.Progress = value, 1f, 1f).SetEase(Ease.OutCubic);
var success = await Context.LevelManager.UnpackLevelPackage(targetFile, destFolder);
if (success)
{
try
{
level =
(await Context.LevelManager.LoadFromMetadataFiles(level.Type, new List<string> {destFolder + "/level.json"}, true))
.First();
onUnpackSucceeded(level);
}
catch (Exception e)
{
Debug.LogError(e);
onUnpackFailed();
}
}
else
{
try
{
onUnpackFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
dialog.Close();
File.Delete(targetFile);
}).Catch(error =>
{
if (aborted || error is OperationCanceledException || (req != null && req.IsAborted))
{
try
{
onDownloadAborted();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
else
{
if (!forceInternational
&& error is RequestException requestException
&& requestException.StatusCode < 400 && requestException.StatusCode >= 500)
{
DownloadAndUnpackLevelDialog(
level,
allowAbort,
onDownloadSucceeded,
onDownloadAborted,
onDownloadFailed,
onUnpackSucceeded,
onUnpackFailed,
true
);
}
else
{
Debug.LogError(error);
try
{
onDownloadFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
dialog.Close();
});
dialog.onUpdate.AddListener(it =>
{
if (!downloading) return;
if (req.Request == null)
{
// Download was cancelled due to Unity
Debug.LogError("UWR download failed");
try
{
onDownloadFailed();
}
catch (Exception e)
{
Debug.LogError(e);
}
dialog.Close();
return;
}
if (totalSize > 0)
{
downloadedSize = req.DownloadedBytes;
it.Progress = downloadedSize * 1.0f / totalSize;
if (batchDownloading)
{
it.Message = "DIALOG_BATCH_DOWNLOADING_P_Q_R_S_T".Get(batchDownloadCurrent, batchDownloadTotal, level.Meta.replacedle, downloadedSize.ToHumanReadableFileSize(),
totalSize.ToHumanReadableFileSize());
}
else
{
it.Message = "DIALOG_DOWNLOADING_X_Y".Get(downloadedSize.ToHumanReadableFileSize(),
totalSize.ToHumanReadableFileSize());
}
}
else
{
it.Message = batchDownloading ? "DIALOG_BATCH_DOWNLOADING_P_Q".Get(batchDownloadCurrent, batchDownloadTotal) : "DIALOG_DOWNLOADING".Get();
}
});
if (allowAbort)
{
dialog.OnNegativeButtonClicked = it =>
{
aborted = true;
req?.Abort();
dialog.Close();
};
}
dialog.Open();
}
19
Source : ProfileScreen.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void UpdateLeaderboard(string mode)
{
ClearLeaderboard();
SpinnerOverlay.Show();
var uri = Context.ApiUrl + "/leaderboard?limit=50";
if (mode == "me") uri += "&user=" + Context.OnlinePlayer.LastProfile.User.Id;
RestClient.GetArray<Leaderboard.Entry>(new RequestHelper
{
Uri = uri,
Headers = Context.OnlinePlayer.GetRequestHeaders(),
EnableDebug = true
}).Then(SetData).CatchRequestError(Debug.LogError).Finally(() => SpinnerOverlay.Hide());
async void SetData(Leaderboard.Entry[] data)
{
try
{
leaderboard.SetData(data);
if (mode == "me")
{
var meEntry = leaderboard.Entries.Find(it => it.Model.Uid == Context.Player.Id);
if (meEntry != null)
{
await UniTask.DelayFrame(0);
leaderboardScrollRect.GetComponent<ScrollRectFocusHelper>()
.CenterOnItem(meEntry.transform as RectTransform);
}
}
await UniTask.DelayFrame(2);
if (LoadedPayload.LeaderboardScrollPosition > -1) leaderboardScrollRect.verticalNormalizedPosition = LoadedPayload.LeaderboardScrollPosition;
}
catch (Exception e)
{
Debug.LogError(e);
}
}
}
19
Source : NavigationBehavior.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
private async void OnDeepLinkReceived(string url)
{
Debug.Log($"Deep link received: {url}");
if (!url.StartsWith("cytoid://")) return;
var token = deepLinkToken = DateTimeOffset.Now;
await UniTask.WaitUntil(() => Context.ScreenManager != null &&
Context.ScreenManager.History.Any(it => it.ScreenId == MainMenuScreen.Id));
if (token != deepLinkToken) return;
if (DeepLinkDisabledScreenIds.Contains(Context.ScreenManager.ActiveScreenId))
{
Debug.Log($"Ignoring, current screen: {Context.ScreenManager.ActiveScreenId}");
return;
}
url = url.Substring("cytoid://".Length);
if (url.StartsWith("levels/"))
{
var id = url.Substring("levels/".Length);
SpinnerOverlay.Show();
RestClient.Get<OnlineLevel>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/levels/{id}"
}).Then(async level =>
{
try
{
if (token != deepLinkToken) return;
foreach (var tag in (replacedetTag[]) Enum.GetValues(typeof(replacedetTag)))
{
if (tag == replacedetTag.PlayerAvatar) continue;
Context.replacedetMemory.DisposeTaggedCachereplacedets(tag);
}
while (Context.ScreenManager.PeekHistory().Let(it => it != null && it.ScreenId != MainMenuScreen.Id))
{
Context.ScreenManager.PopAndPeekHistory();
}
await UniTask.WaitUntil(() => !Context.ScreenManager.IsChangingScreen);
// Resolve level
if (Context.LevelManager.LoadedLocalLevels.ContainsKey(level.Uid))
{
var localLevel = Context.LevelManager.LoadedLocalLevels[level.Uid];
Debug.Log($"Online level {level.Uid} resolved locally");
Context.ScreenManager.History.Push(new Intent(LevelSelectionScreen.Id, null));
Context.ScreenManager.ChangeScreen(GamePreparationScreen.Id, ScreenTransition.In,
payload: new GamePreparationScreen.Payload {Level = localLevel});
}
else
{
Context.ScreenManager.History.Push(new Intent(CommunityHomeScreen.Id, null));
Context.ScreenManager.ChangeScreen(GamePreparationScreen.Id, ScreenTransition.In,
payload: new GamePreparationScreen.Payload {Level = level.ToLevel(LevelType.User)});
}
}
catch (Exception e)
{
Debug.LogError(e);
Dialog.PromptAlert("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
}
}).CatchRequestError(error =>
{
if (token != deepLinkToken) return;
if (error.IsHttpError) {
if (error.StatusCode != 404)
{
throw error;
}
}
Context.Haptic(HapticTypes.Failure, true);
Dialog.Instantiate().Also(it =>
{
it.Message = "DIALOG_COULD_NOT_OPEN_LEVEL_X".Get(id);
it.UsePositiveButton = true;
it.UseNegativeButton = false;
}).Open();
}).Finally(() =>
{
if (token != deepLinkToken) return;
SpinnerOverlay.Hide();
});
}
else
{
Debug.LogError("Unsupported deep link");
}
}
19
Source : LocalPlayerSettings.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Parse(reader.Readreplacedtring());
try
{
var res = new Dictionary<NoteType, T>();
foreach (var type in (NoteType[]) Enum.GetValues(typeof(NoteType)))
{
res[type] = serializer.Deserialize<T>(jObject.GetValue(((int) type).ToString()).CreateReader());
}
return res;
}
catch
{
Debug.LogError($"Incorrect data: {jObject}");
return new Dictionary<NoteType, T>();
}
}
19
Source : CommonExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static Color ToColor(this string rgbString)
{
replacedert.IsTrue(rgbString != null);
if (ColorLookup.ContainsKey(rgbString.ToLower())) return ColorLookup[rgbString.ToLower()];
if (!ColorUtility.TryParseHtmlString(rgbString, out var color))
{
Debug.LogError($"Invalid color string: {rgbString}");
return Color.clear;
}
ColorLookup[rgbString.ToLower()] = color;
return color;
}
19
Source : BundleManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<replacedetBundle> LoadBundle(
string bundleId,
bool loadFromStreamingreplacedets,
bool showDialog,
bool allowAbort = true,
bool instantiate = true,
Action onDownloadSucceeded = default,
Action onDownloadAborted = default,
Action onDownloadFailed = default,
Action onLocallyResolved = default
)
{
if (bundleId == null) throw new ArgumentNullException(nameof(bundleId));
if (!loadFromStreamingreplacedets)
{
Debug.Log($"[BundleManager] Requested remote bundle {bundleId}");
}
else
{
Debug.Log($"[BundleManager] Requested Streamingreplacedets bundle {bundleId}");
}
if (!Catalog.ContainsEntry(bundleId))
{
Debug.LogError($"[BundleManager] {bundleId} does not exist in the catalog!");
return null;
}
Debug.Log($"[BundleManager] Version: {Catalog.GetEntry(bundleId).version}");
if (onLocallyResolved == default) onLocallyResolved = () => { };
if (onDownloadSucceeded == default) onDownloadSucceeded = () => { };
if (onDownloadAborted == default) onDownloadAborted = () => { };
if (onDownloadFailed == default) onDownloadFailed = () => { };
if (IsCached(bundleId))
{
Debug.Log($"[BundleManager] Bundle is cached");
if (IsUpToDate(bundleId)) {
Debug.Log($"[BundleManager] Cached bundle matches version");
onLocallyResolved();
if (!instantiate) return null;
return await LoadCachedBundle(bundleId);
}
}
var downloadUrl = loadFromStreamingreplacedets ? BuiltInBundlesBasePath + bundleId : Context.BundleRemoteFullUrl + bundleId;
Debug.Log($"[BundleManager] URL: {downloadUrl}");
// Check download size
var totalSize = 0ul;
if (!loadFromStreamingreplacedets)
{
if (!Application.isEditor || !Context.Instance.editorUseLocalreplacedetBundles)
{
try
{
using (var headRequest = UnityWebRequest.Head(downloadUrl))
{
await headRequest.SendWebRequest();
if (headRequest.isNetworkError || headRequest.isHttpError)
{
Debug.LogError(headRequest.error);
onDownloadFailed();
return null;
}
totalSize = ulong.Parse(headRequest.GetResponseHeader("Content-Length"));
Debug.Log($"[BundleManager] Download size: {totalSize.ToHumanReadableFileSize()}");
}
}
catch (Exception e)
{
Debug.LogError(e);
onDownloadFailed();
return null;
}
}
else
{
totalSize = 99999999;
}
}
Dialog dialog = null;
var request = UnityWebRequestreplacedetBundle.GetreplacedetBundle(downloadUrl, Catalog.GetEntry(bundleId).version, 0U);
var aborted = false;
if (showDialog)
{
dialog = Dialog.Instantiate();
dialog.Message = "DIALOG_DOWNLOADING".Get();
dialog.UseProgress = true;
dialog.UsePositiveButton = false;
dialog.UseNegativeButton = allowAbort;
dialog.onUpdate.AddListener(it =>
{
if (aborted) return;
var downloadedSize = request.downloadedBytes;
it.Progress = totalSize == 0 ? 0 : downloadedSize * 1.0f / totalSize;
it.Message = "DIALOG_DOWNLOADING_X_Y".Get(downloadedSize.ToHumanReadableFileSize(),
totalSize.ToHumanReadableFileSize());
});
if (allowAbort)
{
dialog.OnNegativeButtonClicked = it =>
{
dialog.Close();
aborted = true;
};
}
dialog.Open();
}
using (request)
{
try
{
request.SendWebRequest();
while (!request.isDone)
{
if (aborted) break;
await UniTask.Yield();
}
}
catch (Exception e)
{
Debug.LogError(e);
onDownloadFailed();
return null;
}
if (aborted)
{
request.Abort();
onDownloadAborted();
return null;
}
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
onDownloadFailed();
return null;
}
if (showDialog) dialog.Close();
onDownloadSucceeded();
if (!instantiate) return null;
if (LoadedBundles.ContainsKey(bundleId))
{
Release(bundleId);
}
var ab = ((DownloadHandlerreplacedetBundle) request.downloadHandler).replacedetBundle;
ab.GetAllreplacedetNames().ForEach(Debug.Log);
LoadedBundles[bundleId] = new Entry {Id = bundleId, replacedetBundle = ab, RefCount = 1};
return ab;
}
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<List<Level>> LoadLevelsOfType(LevelType type)
{
try
{
Directory.CreateDirectory(type.GetDataPath());
}
catch (Exception error)
{
Debug.LogError("Failed to create data folder.");
Debug.LogError(error);
return new List<Level>();
}
var jsonPaths = Directory.EnumerateDirectories(type.GetDataPath())
.SelectMany(it => Directory.EnumerateFiles(it, "level.json"))
.ToList();
Debug.Log($"Found {jsonPaths.Count} levels with type {type}");
return await LoadFromMetadataFiles(type, jsonPaths);
}
19
Source : LocalPlayerSettings.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var data = reader.Readreplacedtring();
try
{
return data.Split(',').Select(it => (TEnum) Enum.Parse(typeof(TEnum), it)).ToHashSet();
}
catch
{
Debug.LogError($"Incorrect data: {data}");
return new HashSet<TEnum>();
}
}
19
Source : OnlinePlayer.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public IPromise<Profile> FetchProfile()
{
var id = Context.Player.Id;
if (IsAuthenticating || Context.IsOnline())
{
// Online
return RestClient.Get<Profile>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/profile/{id}",
Headers = GetRequestHeaders(),
EnableDebug = true
}).Then(profile =>
{
Debug.Log($"Profile: {profile}");
LastProfile = profile ?? throw new InvalidOperationException("Profile is null");
Context.Database.SetProfile(profile);
OnProfileChanged.Invoke(profile);
return profile;
}).CatchRequestError(error =>
{
Debug.LogError("Could not fetch profile.");
Debug.LogError(error);
return null;
});
}
// Offline: Load from DB
return Promise<Profile>.Resolved(LastProfile = Context.Database.GetProfile());
}
19
Source : VideoRenderer.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public override async UniTask Initialize()
{
var targetRenderer = GetTargetRenderer<VideoRenderer>();
if (targetRenderer != null)
{
VideoPlayer = targetRenderer.VideoPlayer;
RawImage = targetRenderer.RawImage;
RenderTexture = targetRenderer.RenderTexture;
RectTransform = targetRenderer.RectTransform;
Canvas = targetRenderer.Canvas;
}
else
{
VideoPlayer = Instantiate(Provider.VideoVideoPlayerPrefab);
RawImage = Instantiate(Provider.VideoRawImagePrefab, Provider.Canvas.transform);
RenderTexture = new RenderTexture(UnityEngine.Screen.width / 2, UnityEngine.Screen.height / 2, 0, RenderTextureFormat.ARGB32);
RectTransform = RawImage.rectTransform;
Canvas = RawImage.GetComponent<Canvas>();
Canvas.overrideSorting = true;
Canvas.sortingLayerName = "Storyboard1";
Clear();
var videoPath = Component.States[0].Path;
if (videoPath == null && Component.States.Count > 1) videoPath = Component.States[1].Path;
if (videoPath == null)
{
throw new InvalidOperationException("Video does not have a valid path");
}
VideoPlayer.gameObject.name = RawImage.gameObject.name = $"$Video[{videoPath}]";
var prefix = "file://";
if (Application.platform == RuntimePlatform.Android && Context.AndroidVersionCode >= 29)
{
Debug.Log("Detected Android 29 or above. Performing magic...");
prefix = ""; // Android Q Unity issue
VideoPlayer.source = VideoSource.Url;
}
var path = prefix + MainRenderer.Game.Level.Path + videoPath;
VideoPlayer.url = path;
VideoPlayer.aspectRatio = VideoAspectRatio.FitOutside;
VideoPlayer.renderMode = VideoRenderMode.RenderTexture;
VideoPlayer.targetTexture = RenderTexture;
RawImage.texture = RenderTexture;
var prepareCompleted = false;
VideoPlayer.prepareCompleted += _ => prepareCompleted = true;
VideoPlayer.Prepare();
var startTime = DateTimeOffset.UtcNow;
await UniTask.WaitUntil(() => prepareCompleted || DateTimeOffset.UtcNow - startTime > TimeSpan.FromSeconds(5));
if (!prepareCompleted)
{
Debug.Log($"Android version code: {Context.AndroidVersionCode}");
Debug.Log($"Video path: {path}");
Debug.LogError("Could not load video. Are you using Android Q or above?");
}
}
}
19
Source : CommonExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static IPromise<T> CatchRequestError<T>(this IPromise<T> promise, Func<RequestException, T> onRejected)
{
return promise.Catch(exception =>
{
if (exception is RequestException requestException)
{
return onRejected(requestException);
}
Debug.LogError($"Exception thrown by promise");
Debug.LogError(exception);
throw exception;
});
}
19
Source : CommonExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static IPromise CatchRequestError<T>(this IPromise<T> promise, Action<RequestException> onRejected)
{
return promise.Catch(exception =>
{
if (exception is RequestException requestException)
{
onRejected(requestException);
}
else
{
Debug.LogError($"Exception thrown by promise");
Debug.LogError(exception);
throw exception;
}
});
}
19
Source : CommonExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static IPromise CatchRequestError(this IPromise promise, Action<RequestException> onRejected)
{
return promise.Catch(exception =>
{
if (exception is RequestAbortedException)
{
Debug.Log("Request canceled by promise");
return;
}
if (exception is RequestException requestException)
{
onRejected(requestException);
}
else
{
Debug.LogError($"Exception thrown by promise");
Debug.LogError(exception);
throw exception;
}
});
}
19
Source : PlayerPrefsExtensions.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public static bool SetStringArray(string key, string[] stringArray)
{
var bytes = new byte[stringArray.Length + 1];
bytes[0] = Convert.ToByte(ArrayType.String); // Identifier
Initialize();
// Store the length of each string that's in stringArray, so we can extract the correct strings in GetStringArray
for (var i = 0; i < stringArray.Length; i++)
{
if (stringArray[i] == null)
{
Debug.LogError("Can't save null entries in the string array when setting " + key);
return false;
}
if (stringArray[i].Length > 255)
{
Debug.LogError("Strings cannot be longer than 255 characters when setting " + key);
return false;
}
bytes[idx++] = (byte) stringArray[i].Length;
}
try
{
PlayerPrefs.SetString(key, Convert.ToBase64String(bytes) + "|" + string.Join("", stringArray));
}
catch
{
return false;
}
return true;
}
19
Source : StartupLogger.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
private void Save()
{
var path = Application.persistentDataPath + "/startup.log";
try
{
File.WriteAllLines(path, entries);
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError("Failed to write startup log");
}
}
19
Source : BundleManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<BundleCatalog> GetRemoteCatalog()
{
var url = Context.BundleRemoteFullUrl + "catalog.json";
Debug.Log($"[BundleManager] Requested catalog from {url}");
var request = UnityWebRequest.Get(url);
request.timeout = 10;
using (request)
{
try
{
await request.SendWebRequest();
}
catch (Exception e)
{
Debug.LogError(e);
return null;
}
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
return null;
}
var text = Encoding.UTF8.GetString(request.downloadHandler.data);
return new BundleCatalog(JObject.Parse(text));
}
}
19
Source : LevelManager.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask<List<Level>> LoadFromMetadataFiles(LevelType type, List<string> jsonPaths, bool forceReload = false)
{
var lowMemory = false;
Application.lowMemory += OnLowMemory;
void OnLowMemory()
{
lowMemory = true;
}
var loadedCount = 0;
var tasks = new List<UniTask>();
var results = new List<Level>();
int index;
for (index = 0; index < jsonPaths.Count; index++)
{
var loadIndex = index;
async UniTask LoadLevel()
{
var timer = new BenchmarkTimer($"Level loader ({loadIndex + 1} / {jsonPaths.Count})") {Enabled = false};
var jsonPath = jsonPaths[loadIndex];
try
{
FileInfo info;
try
{
info = new FileInfo(jsonPath);
if (info.Directory == null)
{
throw new FileNotFoundException(info.ToString());
}
}
catch (Exception e)
{
Debug.LogWarning(e);
Debug.LogWarning($"{jsonPath} could not be read");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var path = info.Directory.FullName + Path.DirectorySeparatorChar;
if (!forceReload && loadedPaths.Contains(path))
{
Debug.LogWarning($"Level from {path} is already loaded");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
Debug.Log($"Loading {loadIndex + 1}/{jsonPaths.Count} from {path}");
if (!File.Exists(jsonPath))
{
Debug.LogWarning($"level.json not found at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
await UniTask.SwitchToThreadPool();
var meta = JsonConvert.DeserializeObject<LevelMeta>(File.ReadAllText(jsonPath));
await UniTask.SwitchToMainThread();
timer.Time("Deserialization");
if (meta == null)
{
Debug.LogWarning($"Invalid level.json at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
if (type != LevelType.Temp && LoadedLocalLevels.ContainsKey(meta.id))
{
if (LoadedLocalLevels[meta.id].Type == LevelType.Tier && type == LevelType.User)
{
Debug.LogWarning($"Community level cannot override tier level");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
if (LoadedLocalLevels[meta.id].Meta.version > meta.version)
{
Debug.LogWarning($"Level to load has smaller version than loaded level");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
loadedPaths.Remove(LoadedLocalLevels[meta.id].Path);
}
// Sort charts
meta.SortCharts();
// Reject invalid level meta
if (!meta.Validate())
{
Debug.LogWarning($"Invalid metadata in level.json at {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {path}");
return;
}
timer.Time("Validate");
var db = Context.Database;
await UniTask.SwitchToThreadPool();
var level = Level.FromLocal(path, type, meta, db);
var record = level.Record;
if (record.AddedDate == DateTimeOffset.MinValue)
{
record.AddedDate = Context.Library.Levels.ContainsKey(level.Id)
? Context.Library.Levels[level.Id].Date
: info.LastWriteTimeUtc;
level.SaveRecord();
}
await UniTask.SwitchToMainThread();
timer.Time("LevelRecord");
if (type != LevelType.Temp)
{
LoadedLocalLevels[meta.id] = level;
loadedPaths.Add(path);
// Generate thumbnail
if (!File.Exists(level.Path + CoverThumbnailFilename))
{
var thumbnailPath = "file://" + level.Path + level.Meta.background.path;
if (lowMemory)
{
// Give up
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
using (var request = UnityWebRequest.Get(thumbnailPath))
{
await request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogWarning(request.error);
Debug.LogWarning($"Cannot get background texture from {thumbnailPath}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})");
return;
}
var coverTexture = request.downloadHandler.data.ToTexture2D();
if (coverTexture == null)
{
Debug.LogWarning(request.error);
Debug.LogWarning($"Cannot get background texture from {thumbnailPath}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ({path})");
return;
}
if (lowMemory)
{
// Give up
Object.Destroy(coverTexture);
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var croppedTexture = TextureScaler.FitCrop(coverTexture, Context.LevelThumbnailWidth,
Context.LevelThumbnailHeight);
if (lowMemory)
{
// Give up
Object.Destroy(coverTexture);
Object.Destroy(croppedTexture);
Debug.LogWarning($"Low memory!");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
return;
}
var bytes = croppedTexture.EncodeToJPG();
Object.Destroy(coverTexture);
Object.Destroy(croppedTexture);
await UniTask.DelayFrame(0); // Reduce load to prevent crash
try
{
File.WriteAllBytes(level.Path + CoverThumbnailFilename, bytes);
Debug.Log(
$"Thumbnail generated {loadIndex + 1}/{jsonPaths.Count}: {level.Id} ({thumbnailPath})");
await UniTask.DelayFrame(0); // Reduce load to prevent crash
}
catch (Exception e)
{
Debug.LogWarning(e);
Debug.LogWarning($"Could not write to {level.Path + CoverThumbnailFilename}");
Debug.LogWarning(
$"Skipped generating thumbnail for {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
}
}
timer.Time("Generate thumbnail");
}
}
results.Add(level);
OnLevelLoadProgress.Invoke(meta.id, ++loadedCount, jsonPaths.Count);
Debug.Log($"Loaded {loadIndex + 1}/{jsonPaths.Count}: {meta.id} ");
timer.Time("OnLevelLoadProgressEvent");
}
catch (Exception e)
{
Debug.LogError(e);
Debug.LogError($"Unexpected error while loading from {jsonPath}");
Debug.LogWarning($"Skipped {loadIndex + 1}/{jsonPaths.Count} from {jsonPath}");
}
timer.Time();
}
tasks.Add(LoadLevel());
}
await UniTask.WhenAll(tasks);
Application.lowMemory -= OnLowMemory;
return results;
}
19
Source : CharacterSelectionScreen.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
protected override void LoadPayload(ScreenLoadPromise promise)
{
SpinnerOverlay.Show();
Context.CharacterManager.GetAvailableCharactersMeta()
.Then(async characters =>
{
try
{
if (Application.isEditor)
{
Debug.Log("Available characters:");
characters.PrintJson();
}
if (characters.Count == 0)
{
// TODO: This should not happen! We have Sayaka
SpinnerOverlay.Hide();
Dialog.PromptGoBack("DIALOG_OFFLINE_FEATURE_NOT_AVAILABLE".Get());
promise.Reject();
return;
}
if (!await Context.BundleManager.DownloadAndSaveCatalog())
{
SpinnerOverlay.Hide();
Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
promise.Reject();
return;
}
SpinnerOverlay.Hide();
var downloadsRequired = 0;
foreach (var meta in characters)
{
if (!Context.BundleManager.IsUpToDate(Characterreplacedet.GetMainBundleId(meta.replacedetId)))
{
downloadsRequired++;
}
}
print($"Number of downloads required: {downloadsRequired}");
var downloaded = 0;
foreach (var meta in characters)
{
var (success, locallyResolved) =
await Context.CharacterManager.DownloadCharacterreplacedetDialog(
Characterreplacedet.GetMainBundleId(meta.replacedetId));
if (success && !locallyResolved)
{
downloaded++;
print("Downloaded " + meta.replacedetId);
}
if (!success)
{
Toast.Next(Toast.Status.Failure, "CHARACTER_FAILED_TO_DOWNLOAD".Get());
}
}
characters.ForEach(it =>
{
if (it.SetId == null) it.SetId = it.Id;
});
IntentPayload.OwnedCharacters.AddRange(characters
.Select((meta, index) => new { meta, index })
.GroupBy(it => it.meta.SetId)
.Select(it => new MergedCharacterMeta { variants = it.OrderBy(x => x.meta.SetOrder).Select(x => x.meta).ToList() })
.OrderBy(it => it.StandardVariant.Date)
);
print($"Number of downloads: {downloaded}");
if (downloaded > downloadsRequired)
{
// Update was performed, which requires player to restart the game
// Why? Too lazy to figure out dynamic reloads...
Dialog.PromptUnclosable("DIALOG_RESTART_REQUIRED".Get());
promise.Reject();
return;
}
if (IntentPayload.OwnedCharacters.Count == 0)
{
Dialog.PromptGoBack("DIALOG_OFFLINE_FEATURE_NOT_AVAILABLE".Get());
promise.Reject();
return;
}
promise.Resolve(IntentPayload);
}
catch (Exception e)
{
Debug.LogError(e);
SpinnerOverlay.Hide();
Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
promise.Reject();
}
})
.CatchRequestError(error =>
{
SpinnerOverlay.Hide();
promise.Reject();
if (!error.IsNetworkError)
{
throw error;
}
Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
});
}
19
Source : Player.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public async UniTask Migrate()
{
await UniTask.DelayFrame(30);
try
{
Context.Database.Let(it =>
{
foreach (var level in Context.LevelManager.LoadedLocalLevels.Values)
{
if (level.Id == null) continue;
var record = new LevelRecord
{
LevelId = level.Id,
RelativeNoteOffset = legacy.GetLevelNoteOffset(level.Id),
AddedDate = legacy.GetAddedDate(level.Id).Let(time =>
time == default ? DateTimeOffset.MinValue : new DateTimeOffset(time)),
LastPlayedDate = legacy.GetLastPlayedDate(level.Id).Let(time =>
time == default ? DateTimeOffset.MinValue : new DateTimeOffset(time)),
BestPerformances = new Dictionary<string, LevelRecord.Performance>(),
BestPracticePerformances = new Dictionary<string, LevelRecord.Performance>(),
PlayCounts = new Dictionary<string, int>(),
};
foreach (var chart in level.Meta.charts)
{
record.PlayCounts[chart.type] = legacy.GetPlayCount(level.Id, chart.type);
if (legacy.HasPerformance(level.Id, chart.type, true))
{
var bestPerformance = legacy.GetBestPerformance(level.Id, chart.type, true).Let(p =>
new LevelRecord.Performance
{
Score = p.Score,
Accuracy = p.Accuracy / 100.0,
});
record.BestPerformances[chart.type] = bestPerformance;
}
if (legacy.HasPerformance(level.Id, chart.type, false))
{
var bestPracticePerformance = legacy.GetBestPerformance(level.Id, chart.type, false).Let(
p =>
new LevelRecord.Performance
{
Score = p.Score,
Accuracy = p.Accuracy / 100.0,
});
record.BestPracticePerformances[chart.type] = bestPracticePerformance;
}
}
Context.Database.SetLevelRecord(record, true);
level.Record = record;
}
});
}
catch (Exception e)
{
Debug.LogError(e);
}
}
19
Source : Storyboard.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public void Parse()
{
if ((bool?) RootObject["compiled"] == true)
{
// Directly load into memory
((JArray) RootObject["texts"]).Select(it => it.ToObject<Text>()).ForEach(it => Texts[it.Id] = it);
((JArray) RootObject["sprites"]).Select(it => it.ToObject<Sprite>()).ForEach(it => Sprites[it.Id] = it);
((JArray) RootObject["videos"]).Select(it => it.ToObject<Video>()).ForEach(it => Videos[it.Id] = it);
((JArray) RootObject["lines"]).Select(it => it.ToObject<Line>()).ForEach(it => Lines[it.Id] = it);
((JArray) RootObject["controllers"]).Select(it => it.ToObject<Controller>()).ForEach(it => Controllers[it.Id] = it);
((JArray) RootObject["note_controllers"]).Select(it => it.ToObject<NoteController>()).ForEach(it => NoteControllers[it.Id] = it);
}
else
{
// Parse
// Templates
if (RootObject["templates"] != null)
{
foreach (var templateProperty in RootObject["templates"].Children<JProperty>())
{
Templates[templateProperty.Name] = templateProperty.Value.ToObject<JObject>();
}
}
void ParseStateObjects<TO, TS>(string rootTokenName, Dictionary<string, TO> addToDictionary,
Action<JObject> tokenPreprocessor = null)
where TO : Object<TS>, new() where TS : ObjectState, new()
{
if (RootObject[rootTokenName] == null) return;
foreach (var childToken in (JArray) RootObject[rootTokenName])
{
foreach (var objectToken in PopulateJObjects((JObject) childToken))
{
tokenPreprocessor?.Invoke(objectToken);
var obj = LoadObject<TO, TS>(objectToken);
if (obj != null)
{
if (addToDictionary.ContainsKey(obj.Id))
{
Debug.LogError($"Storyboard: Redefinition of element {obj.Id}");
continue;
}
addToDictionary[obj.Id] = obj;
}
}
}
}
var timer = new BenchmarkTimer("Storyboard parsing");
ParseStateObjects<Text, TextState>("texts", Texts);
timer.Time("Text");
ParseStateObjects<Sprite, SpriteState>("sprites", Sprites);
timer.Time("Sprite");
ParseStateObjects<Video, VideoState>("videos", Videos);
timer.Time("Videos");
ParseStateObjects<Line, LineState>("lines", Lines);
timer.Time("Lines");
ParseStateObjects<NoteController, NoteControllerState>("note_controllers", NoteControllers, token =>
{
// Note controllers have time default to zero
if (token["time"] == null) token["time"] = 0;
});
timer.Time("NoteController");
ParseStateObjects<Controller, ControllerState>("controllers", Controllers, token =>
{
// Controllers have time default to zero
if (token["time"] == null) token["time"] = 0;
});
timer.Time("Controller");
timer.Time();
// Trigger
if (RootObject["triggers"] != null)
foreach (var objectToken in (JArray) RootObject["triggers"])
Triggers.Add(LoadTrigger(objectToken));
}
}
19
Source : Context.cs
with GNU General Public License v3.0
from Cytoid
with GNU General Public License v3.0
from Cytoid
public string GetAndroidLegacyStoragePath()
{
try
{
using (var javaClreplaced = new AndroidJavaClreplaced("com.unity3d.player.UnityPlayer"))
{
using (var activityClreplaced = javaClreplaced.GetStatic<AndroidJavaObject>("currentActivity"))
{
return activityClreplaced.Call<AndroidJavaObject>("getAndroidStorageFile")
.Call<string>("getAbsolutePath");
}
}
}
catch (Exception e)
{
Debug.LogError("Could not get Android storage path: " + e.Message);
return null;
}
}
19
Source : MicStream.cs
with MIT License
from dag10
with MIT License
from dag10
public static bool CheckForErrorOnCall(int returnCode)
{
switch (returnCode)
{
case (int)ErrorCodes.ALREADY_RECORDING:
Debug.LogError("WARNING: Tried to start recording when you were already doing so. You need to stop your previous recording before you can start again.");
return false;
case (int)ErrorCodes.ALREADY_RUNNING:
Debug.LogError("WARNING: Tried to initialize microphone more than once");
return false;
case (int)ErrorCodes.GRAPH_NOT_EXIST:
Debug.LogError("ERROR: Tried to do microphone things without a properly initialized microphone. \n Do you have a mic plugged into a functional audio system and did you call MicInitialize() before anything else ??");
return false;
case (int)ErrorCodes.NO_AUDIO_DEVICE:
Debug.LogError("ERROR: Tried to start microphone, but you don't appear to have a functional audio device. check your OS audio settings.");
return false;
case (int)ErrorCodes.NO_INPUT_DEVICE:
Debug.LogError("ERROR: Tried to start microphone, but you don't have one plugged in, do you?");
return false;
case (int)ErrorCodes.CHANNEL_COUNT_MISMATCH:
Debug.LogError("ERROR: Microphone had a channel count mismatch internally on device. Try setting different mono/stereo options in OS mic settings.");
return false;
case (int)ErrorCodes.FILE_CREATION_PERMISSION_ERROR:
Debug.LogError("ERROR: Didn't have access to create file in Music library. Make sure permissions to write to Music library are set granted.");
return false;
case (int)ErrorCodes.NOT_ENOUGH_DATA:
// usually not an error, means the device hasn't produced enough data yet because it just started running
return false;
case (int)ErrorCodes.NEED_ENABLED_MIC_CAPABILITY:
Debug.LogError("ERROR: Seems like you forgot to enable the microphone capabilities in your Unity permissions");
return false;
}
return true;
}
19
Source : BasicCursor.cs
with MIT License
from dag10
with MIT License
from dag10
protected virtual void Awake()
{
meshRenderer = gameObject.GetComponent<MeshRenderer>();
if (meshRenderer == null)
{
Debug.LogError("This script requires that your cursor replacedet has a MeshRenderer component on it.");
return;
}
// Hide the Cursor to begin with.
meshRenderer.enabled = false;
// Cache the cursor default rotation so the cursor can be rotated with respect to the original orientation.
cursorDefaultRotation = gameObject.transform.rotation;
}
19
Source : BasicCursor.cs
with MIT License
from dag10
with MIT License
from dag10
protected virtual void Start()
{
gazeManager = GazeManager.Instance;
if (gazeManager == null)
{
Debug.LogError("Must have a GazeManager somewhere in the scene.");
}
if ((GazeManager.Instance.RaycastLayerMask & (1 << gameObject.layer)) != 0)
{
Debug.LogError("The cursor has a layer that is checked in the GazeManager's Raycast Layer Mask. Change the cursor layer (e.g.: to Ignore Raycast) or uncheck the layer in GazeManager: " +
LayerMask.LayerToName(gameObject.layer));
}
}
19
Source : CursorFeedback.cs
with MIT License
from dag10
with MIT License
from dag10
void Awake()
{
if (HandDetectedreplacedet != null)
{
handDetectedGameObject = InstantiatePrefab(HandDetectedreplacedet);
}
else
{
Debug.LogError("Missing a required game object replacedet. Check HandDetectedreplacedet is not null in editor.");
}
}
19
Source : CursorFeedback.cs
with MIT License
from dag10
with MIT License
from dag10
private GameObject InstantiatePrefab(GameObject inputPrefab)
{
GameObject instantiatedPrefab = null;
if (inputPrefab != null && FeedbackParent != null)
{
instantiatedPrefab = GameObject.Instantiate(inputPrefab);
// replacedign parent to be the FeedbackParent
// so that feedback replacedets move and rotate with this parent.
instantiatedPrefab.transform.parent = FeedbackParent.transform;
instantiatedPrefab.transform.localRotation = Quaternion.idenreplacedy;
// Set starting state of the prefab's GameObject to be inactive.
instantiatedPrefab.gameObject.SetActive(false);
}
else
{
Debug.LogError("Missing a required game object replacedet. Check FeedbackParent is not null in editor.");
}
return instantiatedPrefab;
}
19
Source : GestureManipulator.cs
with MIT License
from dag10
with MIT License
from dag10
private void Awake()
{
gestureManager = GestureManager.Instance;
if (gestureManager == null)
{
Debug.LogError(string.Format("GestureManipulator on {0} could not find GestureManager instance, manipulation will not function", name));
}
}
19
Source : HandGuidance.cs
with MIT License
from dag10
with MIT License
from dag10
void Awake()
{
if (HandGuidanceIndicator == null)
{
Debug.LogError("Please include a GameObject for the Hand Guidance Indicator.");
}
if (Cursor == null)
{
Debug.LogError("Please include a GameObject for the Cursor to display the indicator around.");
}
if (HandGuidanceIndicator != null)
{
// Cache the initial rotation of the HandGuidanceIndicator so future rotations
// can be done with respect to this orientation.
defaultHandGuidanceRotation = HandGuidanceIndicator.transform.rotation;
}
// Create an object in the scene for the guidance indicator and default it to not be visible.
handGuidanceIndicatorGameObject = Instantiate(HandGuidanceIndicator);
handGuidanceIndicatorGameObject.SetActive(false);
// Register for hand and finger events to know where your hand
// is being tracked and what state it is in.
InteractionManager.SourceLost += InteractionManager_SourceLost;
InteractionManager.SourceUpdated += InteractionManager_SourceUpdated;
InteractionManager.SourceReleased += InteractionManager_SourceReleased;
}
19
Source : KeywordManager.cs
with MIT License
from dag10
with MIT License
from dag10
void Start()
{
if (KeywordsAndResponses.Length > 0)
{
// Convert the struct array into a dictionary, with the keywords and the keys and the methods as the values.
// This helps easily link the keyword recognized to the UnityEvent to be invoked.
responses = KeywordsAndResponses.ToDictionary(keywordAndResponse => keywordAndResponse.Keyword,
keywordAndResponse => keywordAndResponse.Response);
keywordRecognizer = new KeywordRecognizer(responses.Keys.ToArray());
keywordRecognizer.OnPhraseRecognized += KeywordRecognizer_OnPhraseRecognized;
if (RecognizerStart == RecognizerStartBehavior.AutoStart)
{
keywordRecognizer.Start();
}
}
else
{
Debug.LogError("Must have at least one keyword specified in the Inspector on " + gameObject.name + ".");
}
}
19
Source : SharingMenu.cs
with MIT License
from dag10
with MIT License
from dag10
[MenuItem("HoloToolkit/Sharing Service/Launch Sharing Service", false, 100)]
public static void LaunchSessionServer()
{
string filePathName = @"External\HoloToolkit\Sharing\Server\SharingService.exe";
if (!File.Exists(filePathName))
{
Debug.LogError("Sharing service does not exist at location: " + filePathName);
Debug.LogError("Manually copy SharingService.exe to this path from HoloToolkit-Unity\\External.");
return;
}
Utilities.ExternalProcess.FindAndLaunch(filePathName, @"-local");
}
19
Source : SharingMenu.cs
with MIT License
from dag10
with MIT License
from dag10
[MenuItem("HoloToolkit/Sharing Service/Launch Session Manager", false, 101)]
public static void LaunchSessionUI()
{
string filePathName = @"External\HoloToolkit\Sharing\Tools\SessionManager\x86\SessionManager.UI.exe";
if (!File.Exists(filePathName))
{
Debug.LogError("Session Manager UI does not exist at location: " + filePathName);
Debug.LogError("Manually copy SessionManager.UI.exe to this path from HoloToolkit-Unity\\External.");
return;
}
Utilities.ExternalProcess.FindAndLaunch(filePathName);
}
See More Examples