private static LocalizationData FromJson(string data) { return(JsonUtility.FromJson <LocalizationData>(data)); }
/** * Generate a world using the given .JSON file in 'levelDescriptionJson' */ public void CreateWorldFromLevelDescription() { LevelEntitiesJSON level = JsonUtility.FromJson <LevelEntitiesJSON>(levelDescriptionJsonFiles[levelFileIndex].text); gameController.winConditon = GetWinConditionFromString(level.winCondition); // list of link blocks we are creating levelLinks = new List <LinkBehavior>(); Debug.Log("Loading blocks"); // while generating the level, add things to levelEntities list so it can be destroyed for the next level generated. for (int i = 0; i < level.blocks.Length; i++) { Vector2 blockPos = new Vector2((float)(level.blocks[i].x + (level.blocks[i].width / 2f)), (float)(level.blocks[i].y - (level.blocks[i].height / 2f))); Transform objToInstances = GetAssocInstanceFromType(level.blocks[i].type); if (objToInstances != null) { if (objToInstances == groundPreFab && level.blocks[i].height == 1) { objToInstances = groundTopPreFab; // render it with details on top of the block. } Transform obj = Instantiate(objToInstances, blockPos, Quaternion.identity); Vector2 sizeOfBlock = new Vector3((int)level.blocks[i].width, (int)level.blocks[i].height); obj.GetComponent <SpriteRenderer>().size = sizeOfBlock; obj.GetComponent <BoxCollider2D>().size = sizeOfBlock; obj.GetComponent <LoggableBehavior>().setLogID(level.blocks[i].logId); // ground block levelEntities.Add(obj); } } Debug.Log("Loading player"); // create the player if (level.player != null) { Vector2 loc = new Vector2((float)(level.player.x + (1 / 2f)), (float)(level.player.y - (1 / 2f))); gameController.playerRef = Instantiate(playerPreFab, loc, Quaternion.identity); gameController.playerRef.GetComponent <PlayerBehavior>().gameController = gameController; gameController.playerRef.GetComponent <LoggableBehavior>().setLogID(level.player.logId); levelEntities.Add(gameController.playerRef); // move the backdrop right behind the player initially. backgroundRef.position = gameController.playerRef.position + new Vector3(0, 0, -10); } Debug.Log("Loading goal"); if (level.goalPortal != null) { Vector2 loc = new Vector2((float)(level.goalPortal.x + (1 / 2f)), (float)(level.goalPortal.y - (1 / 2f))); Transform goal = Instantiate(goalPortalPreFab, loc, Quaternion.identity); goal.GetComponent <LoggableBehavior>().setLogID(level.goalPortal.logId); levelEntities.Add(goal); } Debug.Log("Loading helicopter robot"); if (level.helicopterRobot != null) { Vector2 loc = new Vector2((float)(level.helicopterRobot.x + (1 / 2f)), (float)(level.helicopterRobot.y - (1 / 2f))); Transform robot = Instantiate(helicopterRobotPreFab, loc, Quaternion.identity); HelicopterRobotBehavior robotBehavior = robot.GetComponent <HelicopterRobotBehavior>(); robotBehavior.gameController = gameController; robotBehavior.targetLocation = robot.position; robotBehavior.GetComponent <LoggableBehavior>().setLogID(level.helicopterRobot.logId); gameController.helicopterRobotRef = robot; robotBehavior.GetComponent <ContainerEntityBehavior>().refreshChildList(); robotBehavior.getChildLink().GetComponent <LoggableBehavior>().setLogID("helicopter"); robotBehavior.getChildLink().type = LinkBehavior.Type.HELICOPTER; robotBehavior.getChildLink().setVariableName("temp"); robotBehavior.getChildLink().setContainerEntity(robot.GetComponent <ContainerEntityBehavior>()); levelEntities.Add(robot); levelLinks.Add(robotBehavior.GetComponent <ContainerEntityBehavior>().GetChildComponent <LinkBehavior>()); } // corresponding list of IDs telling the link blocks what they should point to when the level is generated List <string> levelLinksConnIds = new List <string>(); List <LinkBehavior> levelLinkComps = new List <LinkBehavior>(); List <ObjectiveBlockBehavior> levelObjectiveBlocks = new List <ObjectiveBlockBehavior>(); List <PlatformBehavior> levelPlatformEntities = new List <PlatformBehavior>(); gameController.platformsToAdd = new List <PlatformBehavior>(); // create the start link Debug.Log("Loading start link"); if (level.startLink != null) { Vector2 loc = new Vector2((float)(level.startLink.x + (1 / 2f)), (float)(level.startLink.y - (1 / 2f))); Transform startLinkTran = Instantiate(linkBlockPreFab, loc, Quaternion.identity); LinkBehavior startLinkBehavior = startLinkTran.GetComponent <LinkBehavior>(); startLinkTran.position = startLinkTran.position + (new Vector3(0, 0, -5)); startLinkBehavior.type = LinkBehavior.Type.START; startLinkBehavior.defaultSprite = startLinkBlockSprite; startLinkBehavior.nullSprite = nullStartLinkBlockSprite; startLinkBehavior.GetComponent <LoggableBehavior>().setLogID(level.startLink.logId); startLinkBehavior.GetComponent <SpriteRenderer>().sprite = startLinkBlockSprite; gameController.startingLink = startLinkBehavior; // set start link reference levelLinks.Add(startLinkBehavior); levelEntities.Add(startLinkTran); levelLinksConnIds.Add(level.startLink.objIDConnectingTo); levelLinkComps.Add(startLinkBehavior); } Debug.Log("Loading external link blocks"); // create the indiv link blocks. for (int i = 0; i < level.linkBlocks.Length; i++) { Vector2 loc = new Vector2((float)(level.linkBlocks[i].x + (1 / 2f)), (float)(level.linkBlocks[i].y - (1 / 2f))); Transform newLink = Instantiate(linkBlockPreFab, loc, Quaternion.identity); newLink.position = newLink.position + (new Vector3(0, 0, -5)); LinkBehavior lb = newLink.GetComponent <LinkBehavior>(); lb.GetComponent <LoggableBehavior>().setLogID(level.linkBlocks[i].logId); levelLinks.Add(lb); levelEntities.Add(newLink); levelLinksConnIds.Add(level.linkBlocks[i].objIDConnectingTo); levelLinkComps.Add(lb); } Debug.Log("Loading objective blocks"); // create the objective blocks (fire) for (int i = 0; i < level.objectiveBlocks.Length; i++) { Vector2 loc = new Vector2((float)(level.objectiveBlocks[i].x + (1 / 2f)), (float)(level.objectiveBlocks[i].y - (1 / 2f))); Transform newOBlock = Instantiate(objectiveBlockPreFab, loc, Quaternion.identity); newOBlock.GetComponent <LoggableBehavior>().setLogID(level.objectiveBlocks[i].logId); levelObjectiveBlocks.Add(newOBlock.GetComponent <ObjectiveBlockBehavior>()); levelEntities.Add(newOBlock); } Debug.Log("Loading instruction blocks"); // create the instruction blocks (question marks) for (int i = 0; i < level.instructionBlocks.Length; i++) { Vector2 loc = new Vector2((float)(level.instructionBlocks[i].x + (1 / 2f)), (float)(level.instructionBlocks[i].y - 1)); Transform newInstructBlock = Instantiate(instructionViewBlockPreFab, loc, Quaternion.identity); newInstructBlock.GetComponent <InstructionViewBlockBehavior>().screenId = level.instructionBlocks[i].screenId; levelEntities.Add(newInstructBlock); } Debug.Log("Loading the platforms"); // create the platforms. Dictionary <string, PlatformBehavior> listPlatformMap = new Dictionary <string, PlatformBehavior>(); for (int i = 0; i < level.singleLinkedListPlatforms.Length; i++) { Vector2 loc = new Vector2((float)(level.singleLinkedListPlatforms[i].x + (3 / 2f)), (float)(level.singleLinkedListPlatforms[i].y - (1 / 2f))); Transform newLLPlatform = Instantiate(singleLinkedListPreFab, loc, Quaternion.identity); PlatformBehavior newPlat = newLLPlatform.GetComponent <PlatformBehavior>(); newPlat.GetComponent <ConnectableEntityBehavior>().incomingConnectionLinks = new List <LinkBehavior>(); newPlat.gameController = gameController; newPlat.GetComponent <ContainerEntityBehavior>().refreshChildList(); newPlat.setValue(level.singleLinkedListPlatforms[i].value); newPlat.GetComponent <LoggableBehavior>().setLogID(level.singleLinkedListPlatforms[i].logId); newPlat.GetComponent <ConnectableEntityBehavior>().incomingConnectionLinks = new List <LinkBehavior>(); listPlatformMap.Add(level.singleLinkedListPlatforms[i].objId, newPlat); newPlat.getChildLink().state = LinkBehavior.State.NORMAL; newPlat.getChildLink().GetComponent <LoggableBehavior>().setLogID("child" + level.singleLinkedListPlatforms[i].logId); newPlat.getChildLink().setContainerEntity(newPlat.GetComponent <ContainerEntityBehavior>()); levelLinks.Add(newPlat.GetComponent <ContainerEntityBehavior>().GetChildComponent <LinkBehavior>()); // add it to the list of blocks for references levelEntities.Add(newLLPlatform); levelLinksConnIds.Add(level.singleLinkedListPlatforms[i].childLinkBlockConnectId); levelLinkComps.Add(newPlat.getChildLink()); levelPlatformEntities.Add(newPlat); newPlat.isInLevel = !level.singleLinkedListPlatforms[i].toAdd; if (level.singleLinkedListPlatforms[i].toAdd == true) { newLLPlatform.gameObject.SetActive(false); gameController.platformsToAdd.Add(newPlat); } } gameController.hudBehavior.setPlatformsToAddText(gameController.platformsToAdd.Count); Debug.Log("Completed loading " + listPlatformMap.Count + " platforms"); Debug.Log("Establishing links "); // establishing links for the link blocks with the platforms for (int i = 0; i < levelLinksConnIds.Count; i++) { if (levelLinksConnIds[i] != null && levelLinksConnIds[i].Length > 0) // if this link has a connection. { string platformId = levelLinksConnIds[i]; if (listPlatformMap[platformId].isInLevel == true) { // establish the connection levelLinkComps[i].ensureReferences(); levelLinkComps[i].setConnectionTo(listPlatformMap[platformId].GetComponent <ConnectableEntityBehavior>()); } } } Debug.Log("Assigning variable names"); string[] varNames = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q", "r", "z", "y" }; int varIndex = 0; // verify that no link blocks are being displayed foreach (LinkBehavior lb in levelLinks) { if (lb.type == LinkBehavior.Type.HELICOPTER) { lb.setVariableName("temp"); } else if (lb.type == LinkBehavior.Type.START) { lb.setVariableName("list.head"); } else { lb.setVariableName(varNames[varIndex++]); } lb.ensureReferences(); lb.UpdateRendering(); } Debug.Log("Updating everything"); // update the win conditions for the objective blocks gameController.setLevelObjectiveBlocksList(levelObjectiveBlocks); gameController.setLevelPlatformEntitiesList(levelPlatformEntities); gameController.updateObjectiveHUDAndBlocks(); gameController.updatePlatformEntities(); gameController.codePanelBehavior.clearCodeText(); gameController.hudBehavior.setLevelOnText(levelFileIndex + 1); gameController.hudBehavior.setPlatformsToAddText(gameController.platformsToAdd.Count); Debug.Log("Done loading world"); }
/// <summary> /// Saves the class containing the information about the last time the image was updated. /// </summary> public void SaveUpdatingImageTime() { PlayerPrefs.SetString(id, JsonUtility.ToJson(updatingImageTime)); }
public static Issues CreateFromJSON(string json) { return(JsonUtility.FromJson <Issues>("{\"issues\":" + json + "}")); }
public static InfoData GetInfoData() { string jsonString = File.ReadAllText(Application.streamingAssetsPath + "/JsonData/InfoData.json"); return(JsonUtility.FromJson <InfoData>(jsonString)); }
//create worker manager, create message listener and start listening to the queue private async Task <int> RunAsync(AgentSettings settings, bool runOnce = false) { try { Trace.Info(nameof(RunAsync)); _listener = HostContext.GetService <IMessageListener>(); if (!await _listener.CreateSessionAsync(HostContext.AgentShutdownToken)) { return(Constants.Agent.ReturnCode.TerminatedError); } HostContext.WritePerfCounter("SessionCreated"); _term.WriteLine(StringUtil.Loc("ListenForJobs", DateTime.UtcNow)); IJobDispatcher jobDispatcher = null; CancellationTokenSource messageQueueLoopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(HostContext.AgentShutdownToken); try { var notification = HostContext.GetService <IJobNotification>(); if (!String.IsNullOrEmpty(settings.NotificationSocketAddress)) { notification.StartClient(settings.NotificationSocketAddress, settings.MonitorSocketAddress); } else { notification.StartClient(settings.NotificationPipeName, settings.MonitorSocketAddress, HostContext.AgentShutdownToken); } // this is not a reliable way to disable auto update. // we need server side work to really enable the feature // https://github.com/Microsoft/vsts-agent/issues/446 (Feature: Allow agent / pool to opt out of automatic updates) bool disableAutoUpdate = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("agent.disableupdate")); bool autoUpdateInProgress = false; Task <bool> selfUpdateTask = null; bool runOnceJobReceived = false; jobDispatcher = HostContext.CreateService <IJobDispatcher>(); while (!HostContext.AgentShutdownToken.IsCancellationRequested) { TaskAgentMessage message = null; bool skipMessageDeletion = false; try { Task <TaskAgentMessage> getNextMessage = _listener.GetNextMessageAsync(messageQueueLoopTokenSource.Token); if (autoUpdateInProgress) { Trace.Verbose("Auto update task running at backend, waiting for getNextMessage or selfUpdateTask to finish."); Task completeTask = await Task.WhenAny(getNextMessage, selfUpdateTask); if (completeTask == selfUpdateTask) { autoUpdateInProgress = false; if (await selfUpdateTask) { Trace.Info("Auto update task finished at backend, an agent update is ready to apply exit the current agent instance."); Trace.Info("Stop message queue looping."); messageQueueLoopTokenSource.Cancel(); try { await getNextMessage; } catch (Exception ex) { Trace.Info($"Ignore any exception after cancel message loop. {ex}"); } if (runOnce) { return(Constants.Agent.ReturnCode.RunOnceAgentUpdating); } else { return(Constants.Agent.ReturnCode.AgentUpdating); } } else { Trace.Info("Auto update task finished at backend, there is no available agent update needs to apply, continue message queue looping."); } } } if (runOnceJobReceived) { Trace.Verbose("One time used agent has start running its job, waiting for getNextMessage or the job to finish."); Task completeTask = await Task.WhenAny(getNextMessage, jobDispatcher.RunOnceJobCompleted.Task); if (completeTask == jobDispatcher.RunOnceJobCompleted.Task) { Trace.Info("Job has finished at backend, the agent will exit since it is running under onetime use mode."); Trace.Info("Stop message queue looping."); messageQueueLoopTokenSource.Cancel(); try { await getNextMessage; } catch (Exception ex) { Trace.Info($"Ignore any exception after cancel message loop. {ex}"); } return(Constants.Agent.ReturnCode.Success); } } message = await getNextMessage; //get next message HostContext.WritePerfCounter($"MessageReceived_{message.MessageType}"); if (string.Equals(message.MessageType, AgentRefreshMessage.MessageType, StringComparison.OrdinalIgnoreCase)) { if (disableAutoUpdate) { Trace.Info("Refresh message received, skip autoupdate since environment variable agent.disableupdate is set."); } else { if (autoUpdateInProgress == false) { autoUpdateInProgress = true; var agentUpdateMessage = JsonUtility.FromString <AgentRefreshMessage>(message.Body); var selfUpdater = HostContext.GetService <ISelfUpdater>(); selfUpdateTask = selfUpdater.SelfUpdate(agentUpdateMessage, jobDispatcher, !runOnce && HostContext.StartupType != StartupType.Service, HostContext.AgentShutdownToken); Trace.Info("Refresh message received, kick-off selfupdate background process."); } else { Trace.Info("Refresh message received, skip autoupdate since a previous autoupdate is already running."); } } } else if (string.Equals(message.MessageType, JobRequestMessageTypes.AgentJobRequest, StringComparison.OrdinalIgnoreCase) || string.Equals(message.MessageType, JobRequestMessageTypes.PipelineAgentJobRequest, StringComparison.OrdinalIgnoreCase)) { if (autoUpdateInProgress || runOnceJobReceived) { skipMessageDeletion = true; Trace.Info($"Skip message deletion for job request message '{message.MessageId}'."); } else { Pipelines.AgentJobRequestMessage pipelineJobMessage = null; switch (message.MessageType) { case JobRequestMessageTypes.AgentJobRequest: var legacyJobMessage = JsonUtility.FromString <AgentJobRequestMessage>(message.Body); pipelineJobMessage = Pipelines.AgentJobRequestMessageUtil.Convert(legacyJobMessage); break; case JobRequestMessageTypes.PipelineAgentJobRequest: pipelineJobMessage = JsonUtility.FromString <Pipelines.AgentJobRequestMessage>(message.Body); break; } jobDispatcher.Run(pipelineJobMessage, runOnce); if (runOnce) { Trace.Info("One time used agent received job message."); runOnceJobReceived = true; } } } else if (string.Equals(message.MessageType, JobCancelMessage.MessageType, StringComparison.OrdinalIgnoreCase)) { var cancelJobMessage = JsonUtility.FromString <JobCancelMessage>(message.Body); bool jobCancelled = jobDispatcher.Cancel(cancelJobMessage); skipMessageDeletion = (autoUpdateInProgress || runOnceJobReceived) && !jobCancelled; if (skipMessageDeletion) { Trace.Info($"Skip message deletion for cancellation message '{message.MessageId}'."); } } else if (string.Equals(message.MessageType, JobMetadataMessage.MessageType, StringComparison.OrdinalIgnoreCase)) { var metadataMessage = JsonUtility.FromString <JobMetadataMessage>(message.Body); jobDispatcher.MetadataUpdate(metadataMessage); } else { Trace.Error($"Received message {message.MessageId} with unsupported message type {message.MessageType}."); } } finally { if (!skipMessageDeletion && message != null) { try { await _listener.DeleteMessageAsync(message); } catch (Exception ex) { Trace.Error($"Catch exception during delete message from message queue. message id: {message.MessageId}"); Trace.Error(ex); } finally { message = null; } } } } } finally { if (jobDispatcher != null) { await jobDispatcher.ShutdownAsync(); } //TODO: make sure we don't mask more important exception await _listener.DeleteSessionAsync(); messageQueueLoopTokenSource.Dispose(); } } catch (TaskAgentAccessTokenExpiredException) { Trace.Info("Agent OAuth token has been revoked. Shutting down."); } return(Constants.Agent.ReturnCode.Success); }
public StageDataRepository(int level, StageDataTable stageDataTable) { var stageData = stageDataTable.stageDataList[level]; _stageDataEntity = JsonUtility.FromJson <StageDataEntity>(stageData.ToString()); }
//Coroutine called from LoadPlayerProgress to load in the progress over time IEnumerator LoadProgressCoroutine(string folderName_) { //If the folder directory doesn't exist if (!Directory.Exists(Application.persistentDataPath + folderName_)) { //We throw an exception because the folder that's supposed to hold the TileGrid.txt file doesn't exist throw new System.ArgumentException("SaveLoadManager.LoadPlayerProgress, The folder directory given does not exist!"); } //If the folder exists but the file doesn't else if (!File.Exists(Application.persistentDataPath + folderName_ + "/" + this.defaultProgressFileName)) { //We throw an exception because the file that we're supposed to load doesn't exist throw new System.ArgumentException("SaveLoadManager.LoadPlayerProgress, The PlayerProgress.txt file for this save does not exist!"); } //Sending out an event to turn on the loading bar EVTData loadEVTData = new EVTData(); loadEVTData.loadData = new LoadDataEVT(true, 7); EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData); loadEVTData.loadData.startingLoad = false; //Getting all of the string data from the TileGrid.txt file string fileData = File.ReadAllText(Application.persistentDataPath + folderName_ + "/" + this.defaultProgressFileName); //De-serializing the player progress from the text file PlayerProgress loadedProgress = JsonUtility.FromJson(fileData, typeof(PlayerProgress)) as PlayerProgress; //Setting the GameData.cs variables GameData.globalReference.currentDifficulty = loadedProgress.difficulty; GameData.globalReference.allowNewUnlockables = loadedProgress.allowNewUnlockables; GameData.globalReference.saveFolder = loadedProgress.folderName; Random.state = loadedProgress.randState; //Setting the CreateTileGrid.cs variables TileMapManager.globalReference.cols = loadedProgress.gridCols; TileMapManager.globalReference.rows = loadedProgress.gridRows; //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//1 //Setting the HUDChallengeRampUpTimer.cs variables HUDChallengeRampUpTimer.globalReference.currentDifficulty = loadedProgress.currentDifficulty; HUDChallengeRampUpTimer.globalReference.currentTimer = loadedProgress.currentDifficultyTimer; //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//2 //Setting the LevelUpManager.cs variable LevelUpManager.globalReference.characterLevel = loadedProgress.characterLevel; //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//3 //Setting the PartyGroup.cs static references if (loadedProgress.partyGroup1 != null) { //Creating a new PartyGroup instance GameObject newPartyObj = GameObject.Instantiate(TileMapManager.globalReference.partyGroupPrefab); PartyGroup partyGroup1 = newPartyObj.GetComponent <PartyGroup>(); //Setting the party variables partyGroup1.combatDistance = loadedProgress.partyGroup1.combatDist; //Looping through all of the character save data for this party group partyGroup1.charactersInParty = new List <Character>(); for (int c = 0; c < loadedProgress.partyGroup1.partyCharacters.Count; ++c) { //If the current character index isn't null, we make a new character instance if (loadedProgress.partyGroup1.partyCharacters[c] != null) { //Creating a new character instance GameObject newCharacterObj = GameObject.Instantiate(TileMapManager.globalReference.defaultCharacterRef.gameObject); Character newCharacter = newCharacterObj.GetComponent <Character>(); //Adding the new character to our new party group partyGroup1.AddCharacterToGroup(newCharacter); //Passing the character save data to the character instance to set all of the component variables newCharacter.LoadCharacterFromSave(loadedProgress.partyGroup1.partyCharacters[c]); } //If the current character index is null, we leave the gap in the list else { partyGroup1.charactersInParty.Add(null); } } //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//4 //Getting the tile grid location of the player group and getting the tile connections TileInfo partyLocation = TileMapManager.globalReference.tileGrid[loadedProgress.partyGroup1.tileCol][loadedProgress.partyGroup1.tileRow]; partyLocation.connectedTiles = new List <TileInfo>() { null, null, null, null, null, null }; for (int coord = 0; coord < partyLocation.connectedTileCoordinates.Count; ++coord) { int col = partyLocation.connectedTileCoordinates[coord].col; int row = partyLocation.connectedTileCoordinates[coord].row; partyLocation.connectedTiles[coord] = TileMapManager.globalReference.tileGrid[col][row]; } partyGroup1.GetComponent <WASDOverworldMovement>().SetCurrentTile(partyLocation); //Setting the static party group reference PartyGroup.globalReference = partyGroup1; //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//5 } //Setting the dead characters from CharacterManager.cs CharacterManager.globalReference.deadCharacters = loadedProgress.deadCharacters; //Setting the quest log for QuestTracker.cs QuestTracker.globalReference.LoadQuestLogData(loadedProgress.questLog); //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//6 //Setting the enemy encounters on the tile grid for CharacterManager.cs for (int e = 0; e < loadedProgress.enemyTileEncounters.Count; ++e) { //Getting the encounter reference EnemyEncounter encounterPrefab = loadedProgress.enemyTileEncounters[e].encounterPrefab.GetComponent <EnemyEncounter>(); //Getting the enemy's tile position TileInfo enemyTile = TileMapManager.globalReference.tileGrid[loadedProgress.enemyTileEncounters[e].encounterTileCol][loadedProgress.enemyTileEncounters[e].encounterTileRow]; //Telling the character manager to instantiate the prefab CharacterManager.globalReference.CreateEnemyEncounter(encounterPrefab, enemyTile); } //Updating the loading bar EventManager.TriggerEvent(LoadDataEVT.eventNum, loadEVTData);//7 yield return(null); }
public IEnumerator <KeyValuePair <string, object> > GetEnumerator() { yield return(new KeyValuePair <string, object>(nameof(Model.FileAndType), JsonUtility.ToJsonString(Model.FileAndType))); yield return(new KeyValuePair <string, object>(nameof(Model.OriginalFileAndType), JsonUtility.ToJsonString(Model.OriginalFileAndType))); yield return(new KeyValuePair <string, object>(nameof(Model.LocalPathFromRepoRoot), Model.LocalPathFromRepoRoot)); yield return(new KeyValuePair <string, object>(nameof(Model.LocalPathFromRoot), Model.LocalPathFromRoot)); yield return(new KeyValuePair <string, object>(nameof(Model.LinkToFiles), Model.LinkToFiles)); yield return(new KeyValuePair <string, object>(nameof(Model.LinkToUids), Model.LinkToUids)); yield return(new KeyValuePair <string, object>(nameof(Model.FileLinkSources), JsonUtility.ToJsonString(Model.FileLinkSources))); yield return(new KeyValuePair <string, object>(nameof(Model.UidLinkSources), JsonUtility.ToJsonString(Model.UidLinkSources))); yield return(new KeyValuePair <string, object>(nameof(Model.Uids), JsonUtility.ToJsonString(Model.Uids))); yield return(new KeyValuePair <string, object>(nameof(Model.ManifestProperties), JsonUtility.ToJsonString(new Dictionary <string, object>((IDictionary <string, object>)Model.ManifestProperties)))); }
public void Save <T>(string key, T data) where T : class { PlayerPrefs.SetString(key, JsonUtility.ToJson(data)); PlayerPrefs.Save(); }
//Function called from CreateTileGrid to load map info from a save directory public void LoadTileGrid(string folderName_) { //If the folder directory doesn't exist if (!Directory.Exists(Application.persistentDataPath + folderName_)) { //We throw an exception because the folder that's supposed to hold the TileGrid.txt file doesn't exist throw new System.ArgumentException("SaveLoadManager.LoadTileGrid, The folder directory given does not exist!"); } //If the folder exists but the file doesn't else if (!File.Exists(Application.persistentDataPath + folderName_ + "/" + this.defaultTileGridFileName)) { //We throw an exception because the file that we're supposed to load doesn't exist throw new System.ArgumentException("SaveLoadManager.LoadTileGrid, The TileGrid.txt file for this save does not exist!"); } //Getting all of the string data from the TileGrid.txt file string fileData = File.ReadAllText(Application.persistentDataPath + folderName_ + "/" + this.defaultTileGridFileName); //Getting the de-serialized TileGridSaveInfo class from the file using the JSON.net converter TileGridSaveInfo tileSaveInfo = JsonConvert.DeserializeObject(fileData, typeof(TileGridSaveInfo)) as TileGridSaveInfo; //Getting the de-serialized 2D list of TileInfo classes for the TileGrid List <List <TileInfo> > loadedTileGrid = new List <List <TileInfo> >(); //Looping through every column of tiles in the tile grid for (int c = 0; c < tileSaveInfo.serializedTileGrid.Count; ++c) { //Creating a new list of tiles to store the tiles in this column List <TileInfo> newTileColumn = new List <TileInfo>(); //Looping through every row of the current column of tiles for (int r = 0; r < tileSaveInfo.serializedTileGrid[0].Count; ++r) { //De-serializing the current tile from the string info using the JsonUtility TileInfo newTile = JsonUtility.FromJson(tileSaveInfo.serializedTileGrid[c][r], typeof(TileInfo)) as TileInfo; newTileColumn.Add(newTile); } //Adding the new column of tiles to the tile grid loadedTileGrid.Add(newTileColumn); } //Looping through all of the tiles in the tile grid to set their connections for (int tc = 0; tc < loadedTileGrid.Count; ++tc) { for (int tr = 0; tr < loadedTileGrid[0].Count; ++tr) { //Initializing the list of connected tiles for the current tile loadedTileGrid[tc][tr].connectedTiles = new List <TileInfo>() { null, null, null, null, null, null }; //Looping through all of the tile connections for the given tile for (int coord = 0; coord < loadedTileGrid[tc][tr].connectedTileCoordinates.Count; ++coord) { int col = loadedTileGrid[tc][tr].connectedTileCoordinates[coord].col; int row = loadedTileGrid[tc][tr].connectedTileCoordinates[coord].row; loadedTileGrid[tc][tr].connectedTiles[coord] = loadedTileGrid[col][row]; } } } //Getting the de-serialized list of TileInfo classes for the city tiles List <TileInfo> loadedCityTiles = new List <TileInfo>(); for (int ct = 0; ct < tileSaveInfo.serializedCityTiles.Count; ++ct) { //De-serializing the current tile from the string info using JsonUtility TileInfo cityTile = JsonUtility.FromJson(tileSaveInfo.serializedCityTiles[ct], typeof(TileInfo)) as TileInfo; loadedCityTiles.Add(cityTile); } //Getting the de-serialized list of TileInfo classes for the dungeon tiles List <TileInfo> loadedDungeonTiles = new List <TileInfo>(); for (int dt = 0; dt < tileSaveInfo.serializedDungeonTiles.Count; ++dt) { //De-serializing the current tile from the string info using JsonUtility TileInfo dungeonTile = JsonUtility.FromJson(tileSaveInfo.serializedDungeonTiles[dt], typeof(TileInfo)) as TileInfo; loadedDungeonTiles.Add(dungeonTile); } //Setting the CreateTileGrid references to the loaded lists of tiles TileMapManager.globalReference.tileGrid = loadedTileGrid; TileMapManager.globalReference.cityTiles = loadedCityTiles; TileMapManager.globalReference.dungeonTiles = loadedDungeonTiles; }
public T Il2CppDeserializeJson <T>(string text) { return(JsonUtility.FromJson <T>(text)); }
public string Il2CppSerializeJson <T>(T il2cppObject, bool shouldIndent = true) where T : Il2CppSystem.Object { return(JsonUtility.ToJson(il2cppObject, shouldIndent)); }
IEnumerator GetHighScoresFromDB() { Debug.Log(TopScoresUrl); UnityWebRequest www = UnityWebRequest.Get(TopScoresUrl); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { // Show results as text Debug.Log(www.downloadHandler.text); Wrapper wrap = JsonUtility.FromJson <Wrapper>("{\"highScores\":" + www.downloadHandler.text + "}"); Debug.Log(wrap.highScores[0].Name); HighScores = wrap.highScores; } HSEntryContainer = transform.Find("HighScoresEntries"); HSEntryTemplate = HSEntryContainer.Find("HighScoresTemplate"); HSEntryTemplate.gameObject.SetActive(false); for (int i = 0; i < HighScores.Length; i++) { Transform HSEntryTransform = Instantiate(HSEntryTemplate, HSEntryContainer); RectTransform HSEntryRectTransform = HSEntryTransform.GetComponent <RectTransform>(); HSEntryRectTransform.anchoredPosition = new Vector2(0, -entryHeight * i); HSEntryTransform.gameObject.SetActive(true); HSEntryTransform.Find("PlayerName").GetComponent <Text>().text = HighScores[i].Name; HSEntryTransform.Find("Score").GetComponent <Text>().text = HighScores[i].Score; if (HighScores[i].Name != "") { HSEntryTransform.Find("HighScoresTemplateBackground").gameObject.SetActive(i % 2 == 0); } else { HSEntryTransform.Find("HighScoresTemplateBackground").gameObject.SetActive(false); } } // HighScores[10] = new HighScore(); // HighScores[10].Name = "----------------------------------------------------"; // HighScores[10].Score = "------------------"; // //Current Players Last Score // HighScores[11] = new HighScore(); // if (GameObject.FindObjectOfType<UpdateScore>()) // { // HighScores[11].Name = UpdateScore._updateScore.gameScoreName; // HighScores[11].Score = UpdateScore._updateScore.gameScore.ToString(); // } // else // { // HighScores[11].Name = ""; // HighScores[11].Score = ""; // } }
public static SceneInfoList CreateFromJSON(string jsonText) { // string json = File.ReadAllText(DATA_FILE_NAME); return(JsonUtility.FromJson <SceneInfoList> (jsonText)); }
public static FileModel Deserialize(Stream stream, IFormatter formatter, Func <Stream, object> contentDeserializer, Func <Stream, IDictionary <string, object> > propertyDeserializer, Action <Stream, FileModel> otherDeserializer) { var sd = new StreamDeserializer(stream); var basicPropertiesSegment = sd.ReadSegment(); var basicProperties = sd.ReadDictionary(basicPropertiesSegment); var contentSegment = sd.ReadNext(basicPropertiesSegment); var content = contentDeserializer(sd.ReadBinaryAsStream(contentSegment)); var result = new FileModel( JsonUtility.Deserialize <FileAndType>(new StringReader((string)basicProperties[nameof(FileModel.FileAndType)])), content, JsonUtility.Deserialize <FileAndType>(new StringReader((string)basicProperties[nameof(FileModel.OriginalFileAndType)])), formatter); // Deserialize basic properties. result.LocalPathFromRepoRoot = (string)basicProperties[nameof(FileModel.LocalPathFromRepoRoot)]; result.LocalPathFromRoot = (string)basicProperties[nameof(FileModel.LocalPathFromRoot)]; result.LinkToFiles = ((object[])basicProperties[nameof(FileModel.LinkToFiles)]).OfType <string>().ToImmutableHashSet(); result.LinkToUids = ((object[])basicProperties[nameof(FileModel.LinkToUids)]).OfType <string>().ToImmutableHashSet(); result.FileLinkSources = JsonUtility.Deserialize <Dictionary <string, List <LinkSourceInfo> > >( new StringReader((string)basicProperties[nameof(FileModel.FileLinkSources)])) .ToImmutableDictionary( pair => pair.Key, pair => pair.Value.ToImmutableList()); result.UidLinkSources = JsonUtility.Deserialize <Dictionary <string, List <LinkSourceInfo> > >( new StringReader((string)basicProperties[nameof(FileModel.UidLinkSources)])) .ToImmutableDictionary( pair => pair.Key, pair => pair.Value.ToImmutableList()); result.Uids = JsonUtility.Deserialize <List <UidDefinition> >( new StringReader((string)basicProperties[nameof(FileModel.Uids)])).ToImmutableArray(); var manifestProperties = (IDictionary <string, object>)result.ManifestProperties; foreach (var pair in JsonUtility.Deserialize <Dictionary <string, object> >( new StringReader((string)basicProperties[nameof(FileModel.ManifestProperties)]))) { manifestProperties[pair.Key] = pair.Value; } // Deserialize properties. var propertySegment = sd.ReadNext(contentSegment); var properties = (IDictionary <string, object>)result.Properties; if (propertyDeserializer != null && propertySegment.ContentType == StreamSegmentType.Binary) { var dictionary = propertyDeserializer(sd.ReadBinaryAsStream(propertySegment)); foreach (var pair in dictionary) { properties[pair.Key] = pair.Value; } } // Deserialize others. var otherSegment = sd.ReadNext(propertySegment); if (otherDeserializer != null && otherSegment.ContentType == StreamSegmentType.Binary) { otherDeserializer(sd.ReadBinaryAsStream(otherSegment), result); } return(result); }
public static ElementsData FromJSON(string json) { return(JsonUtility.FromJson <ElementsData>(json)); }
public IEnumerator Synthesis(string text, Action <TtsResponse> callback, int speed = 5, int pit = 5, int vol = 5, //xg这个地方设置声音 Pronouncer per = Pronouncer.Duxiaoyao //Pronouncer per = Pronouncer.Female ) { yield return(PreAction()); if (tokenFetchStatus == Base.TokenFetchStatus.Failed) { Debug.LogError("Token was fetched failed. Please check your APIKey and SecretKey"); callback(new TtsResponse() { err_no = -1, err_msg = "Token was fetched failed. Please check your APIKey and SecretKey" }); yield break; } var param = new Dictionary <string, string>(); param.Add("tex", text); param.Add("tok", Token); param.Add("cuid", SystemInfo.deviceUniqueIdentifier); param.Add("ctp", "1"); param.Add("lan", "zh"); param.Add("spd", Mathf.Clamp(speed, 0, 9).ToString()); param.Add("pit", Mathf.Clamp(pit, 0, 9).ToString()); param.Add("vol", Mathf.Clamp(vol, 0, 15).ToString()); param.Add("per", ((int)per).ToString()); #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP param.Add("aue", "6"); // set to wav, default is mp3 #endif string url = UrlTts; int i = 0; foreach (var p in param) { url += i != 0 ? "&" : "?"; url += p.Key + "=" + p.Value; i++; } #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV); #else var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG); #endif //打印返回网址 //Debug.Log("[WitBaiduAip]" + www.url); yield return(www.SendWebRequest()); if (string.IsNullOrEmpty(www.error)) { var type = www.GetResponseHeader("Content-Type"); //Debug.Log("[WitBaiduAip]response type: " + type); if (type.Contains("audio")) { #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var clip = DownloadHandlerAudioClip.GetContent(www); var response = new TtsResponse { clip = clip }; #else var response = new TtsResponse { clip = DownloadHandlerAudioClip.GetContent(www) }; #endif callback(response); } else { var textBytes = www.downloadHandler.data; var errorText = Encoding.UTF8.GetString(textBytes); //合成失败 //Debug.Log("[WitBaiduAip]-合成失败:" + errorText); Debug.Log("[WitBaiduAip]-合成失败:"); callback(JsonUtility.FromJson <TtsResponse>(errorText)); } } else { Debug.LogError(www.error + "链接失败"); } }
public void SaveSceneToJson() { #if UNITY_EDITOR SceneSaveData data = new SceneSaveData { gravConst = simControl.GravitationalConstant, isKeplerMotion = _isKeplerMotion, scaleMlt = 1f, timeScale = simControl.timeScale }; if (Application.isPlaying) { data.bodies = new BodySaveData[pool.Count]; for (int i = 0; i < data.bodies.Length; i++) { if (!pool[i].isReady) { data.bodies[i] = new BodySaveData() { scale = pool[i].body.transformRef.localScale.x, position = pool[i].body.position, velocity = pool[i].body.velocity, color = pool[i].meshRend.material.color, mass = pool[i].body.mass, name = pool[i].go.name }; } } data.bodies = data.bodies.Where(b => b != null).ToArray(); } else { var _bodies = GameObject.FindObjectsOfType <CelestialBody>(); data.bodies = new BodySaveData[_bodies.Length]; for (int i = 0; i < data.bodies.Length; i++) { if (_bodies[i].gameObject.activeSelf) { var col = _bodies[i].GetComponent <MeshRenderer>() != null ? _bodies[i].GetComponent <MeshRenderer>().sharedMaterial.color : new Color(); data.bodies[i] = new BodySaveData() { position = _bodies[i].position, velocity = _bodies[i].velocity, mass = _bodies[i].mass, name = _bodies[i].name, scale = _bodies[i].transform.localScale.x, color = col }; } } data.bodies = data.bodies.Where(b => b != null).ToArray(); } string filename = "SavedScene"; string path = Application.dataPath + "/SpaceGravity2D/Demo/JsonData/"; int t = 0; while (t < 100 && System.IO.File.Exists(path + filename + ".txt")) { t++; filename = "SavedScene (" + t + ")"; } System.IO.File.WriteAllText(path + filename + ".txt", JsonUtility.ToJson(data, true)); UnityEditor.AssetDatabase.Refresh(); Debug.Log("SpaceGravity2D: Objects saved to " + filename); #endif }
//starts dialogue system and starts load process private IEnumerator ResumeDialogue() { GameStateData gsd; string loadPath = Application.persistentDataPath + "/saveData.json"; using (StreamReader r = new StreamReader(loadPath)) { string json = r.ReadToEnd(); gsd = JsonUtility.FromJson <GameStateData>(json); } GameObject.FindGameObjectWithTag("Player").transform.GetChild(0).GetComponent <PauseMenu>().LoadGame(gsd); //dialogue string path = Application.streamingAssetsPath + "/loadDialogue.txt"; string dialogue = File.ReadAllText(path); string[] lines = dialogue.Split('%'); float timer = 0; for (int i = 0; i < lines.Length; i++) { mText.text = lines[i]; timer = 0; while (timer < fadeTime) { fader.alpha = 1 - (timer / fadeTime); timer += Time.deltaTime; yield return(null); } fader.alpha = 0; timer = 0; while (timer < readTime) { timer += Time.deltaTime; yield return(null); } timer = 0; while (timer < fadeTime) { fader.alpha = (timer / fadeTime); timer += Time.deltaTime; yield return(null); } fader.alpha = 1; } //load dialogue specific mText.text = "Trees Planted: " + gsd.trees.Length; timer = 0; while (timer < fadeTime) { fader.alpha = 1 - (timer / fadeTime); timer += Time.deltaTime; yield return(null); } fader.alpha = 0; timer = 0; while (timer < readTime) { timer += Time.deltaTime; yield return(null); } timer = 0; while (timer < fadeTime) { fader.alpha = (timer / fadeTime); timer += Time.deltaTime; yield return(null); } fader.alpha = 1; mText.text = ""; skipText.text = ""; timer = 0; bg.alpha = 0; while (timer < fadeTime) { fader.alpha = 1 - (timer / fadeTime); timer += Time.deltaTime; yield return(null); } fader.alpha = 0; GameObject.FindGameObjectWithTag("Player").transform.GetChild(0).GetComponent <ItemManager>().enabled = true; GameObject.FindGameObjectWithTag("Player").transform.GetChild(0).GetComponent <MeditationManager>().enabled = true; Destroy(transform.gameObject); }
public static SceneInfo CreateFromJSON(string json) { return(JsonUtility.FromJson <SceneInfo>(json)); }
private void GeneratePrefabs(string targetPath) { // confirmation dialog if (overwrite) { bool check = EditorUtility.DisplayDialog("Overwrite Prefabs?", "Are you sure you want to overwrite existing prefabs? This is permanent.", "Proceed", "Cancel"); if (!check) { return; } } CardController.Faction faction; // make the path relative to the project if (targetPath.StartsWith(Application.dataPath)) { // get faction name based on folder name string factionName = targetPath.Substring(Application.dataPath.Length).Substring("/Resources/Cards/".Length); var result = System.Enum.TryParse <CardController.Faction>(factionName, out faction); if (!result) { Debug.LogError("could not parse faction folder name to CardController enum"); return; } Debug.Log("Matched as faction: " + faction); targetPath = "Assets" + targetPath.Substring(Application.dataPath.Length) + "/"; } else { Debug.LogError("invalid folder selected"); return; } // resources.load expects a different relative path, prep that string assetPathPrefix = "Assets/Resources/"; string resourcesLoadPath = targetPath; if (resourcesLoadPath.StartsWith(assetPathPrefix)) { resourcesLoadPath = resourcesLoadPath.Substring(assetPathPrefix.Length); } cardsJson = Resources.Load(resourcesLoadPath + "cards"); if (!cardsJson) { Debug.LogError("cards json was not found in the folder"); return; } if (!cardsJson || targetPath == "" || !cardPrefab) { Debug.LogError("not the right stuff supplied"); return; } // save data as per CardDataHolder CardDataCollection cardDataCollection = JsonUtility.FromJson <CardDataCollection>(cardsJson.ToString()); int generatedCount = 0; int destroyedCount = 0; int skippedCount = 0; int errorCount = 0; List <string> devNameList = new List <string>(); foreach (CardDataHolder card in cardDataCollection.cards) { if (card.devName == "") { Debug.LogWarning("empty devName, likely incomplete card, skipping"); errorCount += 1; continue; } // check to see if prefab exists, handle as specified GameObject existingPrefab = null; bool prefabExists = true; existingPrefab = (GameObject)Resources.Load(resourcesLoadPath + card.devName); if (existingPrefab == null) { prefabExists = false; } if (!overwrite && prefabExists) { // we'll need to add these ones to the list of cards to make sure we get all devNameList.Add(existingPrefab.name); skippedCount += 1; continue; } else if (overwrite && prefabExists) { DestroyImmediate(existingPrefab, true); destroyedCount += 1; } // instantiate the CardBase prefab - this will bring all 3D stuff etc with it // add components and set properties as required GameObject newCard = (GameObject)PrefabUtility.InstantiatePrefab(cardPrefab); newCard.name = card.devName; CardController newCard_CC = newCard.GetComponent <CardController>(); newCard_CC.displayName = card.Name; newCard_CC.faction = faction; CardController.SlotType newCardSlot; if (System.Enum.TryParse <CardController.SlotType>(card.SlotType, out newCardSlot)) { // these two TP only newCard_CC.effectText = card.Effect; newCard_CC.SetBaseStats(card.Cost, card.Power, card.Initiative, card.Armour, card.Life); // todo: remove these when effects are more implemented newCard_CC.claimText = card.Claim; newCard_CC.specialText = card.Special; newCard_CC.passiveText = card.Passive; newCard_CC.effectText = card.Effect; // do we need to store this? newCard_CC.devName = card.devName; newCard_CC.slotType = newCardSlot; } else { Debug.LogError("Invalid slottype, skipping"); errorCount += 1; continue; } // check over every Effect Type defined, check their custom attribute to see if they are for this card foreach (Type t in GetAllEffectTypes()) { newCard.AddComponent(t); } foreach (var comp in newCard.GetComponents <CardEffectBase>()) { if (!comp.GetType().CustomAttributes.First().AttributeType.Name.Contains("064_ophelia")) { DestroyImmediate(comp); } else { if (comp.effectType == GamePlayConstants.EffectType.Claim && newCard_CC.claimText != "") { comp.fullText = newCard_CC.claimText; } if (comp.effectType == GamePlayConstants.EffectType.Passive && newCard_CC.passiveText != "") { comp.fullText = newCard_CC.passiveText; } if (comp.effectType == GamePlayConstants.EffectType.Special && newCard_CC.specialText != "") { comp.fullText = newCard_CC.specialText; } if (comp.effectType == GamePlayConstants.EffectType.TurningPoint && newCard_CC.effectText != "") { comp.fullText = newCard_CC.effectText; } } } // convert the gameobject to a prefab and store in the specified folder string localPath = targetPath + newCard.name + ".prefab"; PrefabUtility.SaveAsPrefabAsset(newCard, localPath); // add the devName to list of devnames, with prefix for loading devNameList.Add("Cards/" + faction + "/" + newCard.name); // destory the gameobject we created in the scene DestroyImmediate(newCard); generatedCount += 1; } // save all the devnames SaveCardList(devNameList, faction); Debug.Log("Finished. Generated " + generatedCount + ", Destroyed " + destroyedCount + ", Skipped " + skippedCount + ", Errored " + errorCount); }
private static void Export() { var sceneLoadCtl = Selection.activeGameObject.GetComponent <SceneObjectLoadController>(); // SceneInfoForServer scene_info = Selection.activeTransform.GetComponent<SceneInfoForServer>(); if (sceneLoadCtl == null) { EditorUtility.DisplayDialog("Warning", "you must select a GameObject with SceneObjectLoadController component", "Ok"); return; } sceneLoadCtl.ResetAllData(); string defaultFolder = SavePath + Selection.activeGameObject.name; string save_path = EditorUtility.SaveFilePanel("Save Scene Info File", defaultFolder, "scene_info", "json"); if (save_path == "") { return; } ResPathDic = new Dictionary <string, int>(); ResPathList = new List <string>(); CurResID = 0; SceneInfo export_info = new SceneInfo(); //先把所有选中的场景节点信息导出来 export_info.ObjectInfoList = new List <SceneStaticObject>(); PickChild(Selection.activeTransform, export_info.ObjectInfoList, Vector3.one); if (export_info.ObjectInfoList.Count <= 0) { Debug.Log("export scene info failed!"); return; } float maxX, maxY, maxZ, minX, minY, minZ; maxX = maxY = maxZ = -Mathf.Infinity; minX = minY = minZ = Mathf.Infinity; // Debug.Log("export_info.ObjectInfoList.Count : "+export_info.ObjectInfoList.Count.ToString()); for (int i = 0; i < export_info.ObjectInfoList.Count; i++) { maxX = Mathf.Max(export_info.ObjectInfoList[i].Bounds.max.x, maxX); maxY = Mathf.Max(export_info.ObjectInfoList[i].Bounds.max.y, maxY); maxZ = Mathf.Max(export_info.ObjectInfoList[i].Bounds.max.z, maxZ); minX = Mathf.Min(export_info.ObjectInfoList[i].Bounds.min.x, minX); minY = Mathf.Min(export_info.ObjectInfoList[i].Bounds.min.y, minY); minZ = Mathf.Min(export_info.ObjectInfoList[i].Bounds.min.z, minZ); } Vector3 size = new Vector3(maxX - minX, maxY - minY, maxZ - minZ); Vector3 center = new Vector3(minX + size.x / 2, minY + size.y / 2, minZ + size.z / 2); export_info.Bounds = new Bounds(center, size); SaveLightInfo(export_info); BornInfo[] born_list = Selection.activeTransform.GetComponentsInChildren <BornInfo>(); export_info.BornList = new List <BornInfoData>(); foreach (var item in born_list) { export_info.BornList.Add(new BornInfoData(item.GetUnityPos(), item.born_id)); } MonsterInfo[] mons_list = Selection.activeTransform.GetComponentsInChildren <MonsterInfo>(); export_info.MonsterList = new List <int>(); foreach (var item in mons_list) { if (!export_info.MonsterList.Exists(x => x == item.monster_type_id)) { export_info.MonsterList.Add(item.monster_type_id); } } export_info.ResPathList = ResPathList; string json = JsonUtility.ToJson(export_info, true); File.WriteAllText(save_path, json); Debug.Log("export succeed : " + save_path + " content : " + json); int max_create_num = 19; int min_create_num = 0; sceneLoadCtl.Init(export_info.Bounds.center, export_info.Bounds.size, true, max_create_num, min_create_num, SceneSeparateTreeType.QuadTree); Debug.Log("export_info.ObjectInfoList.Count : " + export_info.ObjectInfoList.Count.ToString()); for (int i = 0; i < export_info.ObjectInfoList.Count; i++) { sceneLoadCtl.AddSceneBlockObject(export_info.ObjectInfoList[i]); } }
private void ProcessMessage(ref uOSC.Message message) { //メッセージアドレスがない、あるいはメッセージがない不正な形式の場合は処理しない if (message.address == null || message.values == null) { StatusMessage = "Bad message."; return; } if (manager.receiver.isLoading) { //ローカル読込中は処理しない return; } if (manager.status.DVRC_AuthState != "AUTHENTICATION_OK") { //ログインしていない場合は受け付けない return; } if (message.address == "/VMC/Ext/Remote" && (message.values[0] is string) && //service (message.values[1] is string) //json ) { string service = message.values[0] as string; string json = message.values[1] as string; if (service == "dmmvrconnect") { var connect = JsonUtility.FromJson <dmmvrconnect>(json); if (user_id != connect.user_id || avatar_id != connect.avatar_id) { user_id = connect.user_id; avatar_id = connect.avatar_id; //メインスレッドに渡す synchronizationContext.Post(async _ => { Debug.Log("Avatar loading from Connect..."); var current_user = await Authentication.Instance.Okami.GetCurrentUserAsync(); if (user_id == current_user.id) { var avatar = await Authentication.Instance.Okami.GetAvatarAsync(current_user.id, avatar_id); Debug.Log(avatar); if (avatar != null) { await manager.LoadAvatarFromDVRSDK(avatar); } else { Debug.LogError("Avatar loading from Connect... Failed!"); } Debug.Log("Load from connect OK"); } else { Debug.Log("User id unmatch"); } }, null); } } else { StatusMessage = "Unknown service: " + service; } } }
void ReadTrelloCredentials() { TextAsset txtAsset = (TextAsset)Resources.Load("Credentials/credentials_trello_workAR", typeof(TextAsset)); credentials = JsonUtility.FromJson <TrelloCrendentials>(txtAsset.text); }
private static void CreateOperatorProperty() { string filePath = Application.dataPath + "/Text Assets/operator_property.json"; UserData1 userData1 = new UserData1 { operatorsProperty = new OperatorProperty[12] }; userData1.operatorsProperty = new[] { new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 0, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "爆破手", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 1, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "野兽", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 2, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "士官长", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 3, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "雷神", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 4, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "战争机器", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 5, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "星舰长", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 6, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "女猎手", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 7, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "探险者", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 8, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "药剂师", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 9, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "剑士", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 10, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "魅影", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 }, new OperatorProperty { currentHealth = 3, currentMapIndex = 0, currentSkillLevel = new[] { 1, 1, 1, 1 }, index = 11, maxHealth = 3, maxSkillLevel = new[] { 4, 4, 4, 4 }, name = "格斗家", skillCooldown = new[] { 0, 0, 0, 0 }, skillIndex = new[] { 0, 3, 4, 5 }, skillPoint = 3 } }; File.WriteAllText(filePath, JsonUtility.ToJson(userData1, true), Encoding.UTF8); AssetDatabase.Refresh(); }
public override void Set(ArgEntry arg) { var json = System.IO.File.ReadAllText(arg.Value); JsonUtility.FromJsonOverwrite(json, m_Obj); }
public override void Write(string pathToResourceGroup) { // Create the ARReferenceImage in Xcode var pathToReferenceImage = Path.Combine(pathToResourceGroup, filename); Directory.CreateDirectory(pathToReferenceImage); // Copy or create the texture as a file in Xcode var textureFilename = Path.GetFileName(m_TexturePath); string destinationPath = Path.Combine(pathToReferenceImage, textureFilename); if (m_ImageBytes == null) { File.Copy(m_TexturePath, destinationPath, true); } else { var textureImporter = AssetImporter.GetAtPath(m_TexturePath) as TextureImporter; if (textureImporter != null) { if (textureImporter.npotScale != TextureImporterNPOTScale.None) { Debug.LogWarningFormat( "The import settings for texture at {0} cause its dimensions to be rounded to a power of two. " + "To use this texture with ARKit, it will be exported to a PNG with the rounded dimensions. " + "This may result in unexpected behavior. " + "You can change this on the texture's import settings under Advanced > Non Power of 2, or " + "use a JPG or PNG, since those formats can be used directly rather than exported with the texture importer settings.", m_TexturePath); } } // If the image is some other format, then attempt to convert it to a PNG textureFilename = Path.ChangeExtension(textureFilename, ".png"); destinationPath = Path.ChangeExtension(destinationPath, ".png"); // m_ImageBytes was read in the constructor File.WriteAllBytes(destinationPath, m_ImageBytes); } // Create the Contents.json var contents = new Json.ReferenceImage { info = new Json.AuthorInfo { version = 1, author = "unity" }, images = new Json.FilenameWithIdiom[] { new Json.FilenameWithIdiom { filename = textureFilename, idiom = "universal" } }, properties = new Json.ImageProperties { width = m_Width } }; File.WriteAllText(Path.Combine(pathToReferenceImage, "Contents.json"), JsonUtility.ToJson(contents)); }
private void CreateGameData() => File.WriteAllText($@"{Application.persistentDataPath}\cnovell.c4ke", JsonUtility.ToJson(m_gameData));
//json utility methods private static string ToJson(LocalizationData data) { return(JsonUtility.ToJson(data)); }