public DialogueNode[] GetDialogueNode(string dialogueId) { if (json != null) { JArray relevantDialogue = (JArray)json ["dialogs"] [dialogueId]; if (relevantDialogue == null) { relevantDialogue = (JArray)json ["dialogs"] ["Error"]; } JArray speakers = (JArray)json ["speakers"]; List<DialogueNode> dialogue = new List<DialogueNode>(); foreach (JToken line in relevantDialogue) { JToken speaker = speakers.First(e => e ["name"].Value<string>() == line ["speaker"].Value<string>()); DialogueNode node = new DialogueNode(line ["text"].Value<string>(), speaker ["appearname"].Value<string>(), line ["voicefile"].Value<string>(), speaker ["picture"].Value<string>()); dialogue.Add(node); } return dialogue.ToArray(); } throw new NullReferenceException("json not loaded in GetDialogueNode"); }
void Update () { if (auto_playing && VNSceneManager.current_conversation != null) { // Check if our current node is a dialogue node Node cur_node = VNSceneManager.current_conversation.Get_Current_Node(); if (cur_node is DialogueNode) { DialogueNode dialogue = (DialogueNode)cur_node; if(AudioListener.volume == 0) { isAudioMuted = true; auto_play_delay = 1.5f; } else { isAudioMuted = false; auto_play_delay = 1.0f; } if ((dialogue.done_printing)// || !UIManager.ui_manager.entire_UI_panel.activeSelf) // Done printing, or UI panel is hidden && (dialogue.done_voice_clip || isAudioMuted) && !button_to_be_pressed) { cur_dialogue = dialogue; button_to_be_pressed = true; Debug.Log("Autoplaying"); // Done printing and voice, wait a second or two then press the button StartCoroutine(Delay_Button_Press()); } } } }
public DialogueManager() { NodeCurrent = null; TopicCurrent = null; State = DialogueState.INACTIVE; }
public DialogueSequence(TextAsset nodeFile) : this() { System.IO.StringReader sr = new System.IO.StringReader(nodeFile.text); while(sr.Peek() != -1 && sr.ReadLine().Trim().Equals("NODE:")) { // Read each node in. string name = sr.ReadLine().Trim().Substring(6); string speaker = sr.ReadLine().Trim().Substring(9); string text = sr.ReadLine().Trim().Substring(6); string tmp; while( (tmp = sr.ReadLine().Trim()) != "ENDTEXT") { text += tmp + " "; } DialogueNode newNode = new DialogueNode(name, speaker, text); while( (tmp = sr.ReadLine().Trim()) == "OPTION:" ) { name = sr.ReadLine().Trim(); text = sr.ReadLine().Trim(); options.Add( new Option{ from = newNode.name, to = name, description = text } ); } this.AddNode(newNode); } //TODO Verify that all options are valid. }
public void RemoveNode(DialogueNode n) { foreach(DialogueNode node in GetNodeList()) { if(n == node) { GetNodeList().Remove(n); } } }
private void ArrangeGatherChildren(DialogueNode node, int level, List<List<DialogueEntry>> tree) { if (node == null) return; while (tree.Count <= level) { tree.Add(new List<DialogueEntry>()); } if (!tree[level].Contains(node.entry)) tree[level].Add(node.entry); if (node.hasFoldout) { foreach (var child in node.children) { ArrangeGatherChildren(child, level + 1, tree); } } }
public void Display(DialogueNode dn) { Type = dn.GetType(); DisplayText.Clear(); if(Type == DialogueNode.NodeType.Line) { DialogueLine dl = (DialogueLine)dn; CharacterData character = db.GetCharacter(dl.GetSpeakerId()); TextColor = character.GetTextColor(); string s = character.GetName(); if(dl.GetSpeakerId() == 0) s += " (You)"; s += ":\n\"" + dm.AddNames(dl.GetText()) + "\""; DisplayText.Add(s); } else if(Type == DialogueNode.NodeType.Choice) { TextColor = Color.white; List<Choice> lc = ((DialogueChoice)dn).GetChoices(); for(int i = 0; i < lc.Count; i++) DisplayText.Add(dm.AddNames(lc[i].GetText())); } }
void OnGUI() { GUI.skin = skin; if(isTalking) { //convoStart() int i = 0; if(!boxTexture) { Debug.LogError ("Dialogue Texture missing"); return; } GUI.DrawTexture (new Rect(xPos - 40 , yPos - 35 , boxWidth + 70 , boxHeight), boxTexture, ScaleMode.StretchToFill, true, 10.0F); GUI.Label (new Rect(xPos,yPos, boxWidth, boxHeight), currentNode.GetDialogue ()); GUI.Label (new Rect(xPos,yPos - 25, Screen.width - 10, 200), currentNode.GetActorName ()+ ":"); int x = 370; foreach(DialogueEdge edge in currentNode.GetNeighbors()) { int y = (int)yPos + (boxHeight + 5); if(edge.GetTo().GetCondition() != null) { if(!m.CheckCondition(edge.GetTo().GetCondition())) { continue; } } if(GUI.Button(new Rect(x,y,330,120), edge.GetTo().GetDialogue())) { //if there are replies if(edge.GetTo().GetNeighbors().Count >= 1) { //broken down /* List<DialogueEdge> lol = edge.GetTo().GetNeighbors(); DialogueEdge lolz = (DialogueEdge)lol[0]; currentNode = (DialogueNode)lolz.GetTo(); */ //simplified currentNode = edge.GetTo().GetNeighbors()[0].GetTo(); } else { //Convo is over Debug.Log ("Conversation Over"); isTalking = false; NPCstate = edge.GetTo().GetNextState(); currentNode = GetStartNode(NPCstate); //convoEnd() } } x+= 340; i++; } } }
public static List <DialogueNode> GetNodeResponses(string nodeKey) { DialogueNode node = GetNode(nodeKey); return(GetNodeResponses(node)); }
public void TestDialogue_Transition() { var you = YouInARoom(out IWorld w); var node = new DialogueNode() { Identifier = new Guid("4f87d23d-ede9-4684-9b33-840a3e8fbc39"), Body = new List <TextBlock> { new TextBlock { Text = "Hey" } }, Options = new List <DialogueOption>() { new DialogueOption() { Text = "Leave" }, new DialogueOption() { Text = "Talk to Hobgoblin", Transition = new Guid("071b853e-f663-4caf-98c1-951c9961a7ed") } } }; var response = new DialogueNode() { Body = new List <TextBlock> { new TextBlock { Text = "That's me, the goblin!" } }, Identifier = new Guid("13a20154-3ec7-43bb-841d-809f49a62ba0") }; w.Dialogue.AllDialogues.Add(response); w.Dialogue.AllDialogues.Add(node); you.CurrentLocation.Dialogue.Next = new Guid("4f87d23d-ede9-4684-9b33-840a3e8fbc39"); w.Dialogue.Run(new SystemArgs(w, GetUI("Leave"), 0, you, you.CurrentLocation, Guid.Empty), node); //there are no goblins here! Assert.Throws <OptionNotAvailableException>(() => w.Dialogue.Run(new SystemArgs(w, GetUI("Talk to Hobgoblin"), 0, you, you.CurrentLocation, Guid.Empty), node)); var goblin = new Npc("Hobgob", you.CurrentLocation) { Identifier = new Guid("071b853e-f663-4caf-98c1-951c9961a7ed") }; //goblin has nothing to say so still should not be offered Assert.Throws <OptionNotAvailableException>(() => w.Dialogue.Run(new SystemArgs(w, GetUI("Talk to Hobgoblin"), 0, you, you.CurrentLocation, Guid.Empty), node)); goblin.Dialogue.Next = new Guid("13a20154-3ec7-43bb-841d-809f49a62ba0"); //now transition should work var args = new SystemArgs(w, GetUI("Talk to Hobgoblin"), 0, you, you.CurrentLocation, Guid.Empty); //you were chating to the room Assert.AreEqual(you.CurrentLocation, args.Recipient); w.Dialogue.Run(args, node); //now you are chatting to the goblin Assert.AreEqual(goblin, args.Recipient); //if they are dead don't allow transitions either! goblin.Dead = true; //goblin has nothing to say so still should not be offered Assert.Throws <OptionNotAvailableException>(() => w.Dialogue.Run(new SystemArgs(w, GetUI("Talk to Hobgoblin"), 0, you, you.CurrentLocation, Guid.Empty), node)); }
public void Load(DialogueNode d, NPC n) { //print("new dialog select"); // Debug.Log("Loading "+d.name+", "+n.name); npcName.text = n.name; if (n.image != null) { npcImage.sprite = n.image; } npcSpeech.text = d.speech; dialog1 = responseOneEnabler.GetComponent <Button>(); dialog2 = responseTwoEnabler.GetComponent <Button>(); dialogEnd = bye.GetComponent <Button>(); dialogDesign.SetActive(true); bye.SetActive(true); byeButton.SetActive(false); EventSystem.current.SetSelectedGameObject(null); UIManager.Instance.SetAsActive(this); //one dialog node if (d.GetNodeOne() != null && d.GetNodeTwo() == null) { //print("set selected to dialog1 button"); EventSystem.current.SetSelectedGameObject(responseOneEnabler); //set navigation for one dialog node to exit button Navigation nav = dialog1.navigation; nav.mode = Navigation.Mode.Explicit; nav.selectOnDown = dialogEnd; nav.selectOnUp = dialogEnd; dialog1.navigation = nav; //set navigation for exit to one dialog button nav = dialogEnd.navigation; nav.mode = Navigation.Mode.Explicit; nav.selectOnDown = dialog1; nav.selectOnUp = dialog1; dialogEnd.navigation = nav; responseOneEnabler.SetActive(true); optionOne.text = d.GetTextOne(); responseTwoEnabler.SetActive(false); optionTwo.text = d.GetTextTwo(); dialog1.Select(); } //two dialog node else if (d.GetNodeOne() != null && d.GetNodeTwo() != null) { //print("set selected to dialog1 button"); EventSystem.current.SetSelectedGameObject(responseOneEnabler); //set navigation for one dialog node to up->end, down->two Navigation nav = dialog1.navigation; nav.mode = Navigation.Mode.Explicit; nav.selectOnDown = dialog2; nav.selectOnUp = dialogEnd; dialog1.navigation = nav; //set navigation for two dialog node to up->one, down->end nav = dialog2.navigation; nav.mode = Navigation.Mode.Explicit; nav.selectOnDown = dialogEnd; nav.selectOnUp = dialog1; dialog2.navigation = nav; //set navigation for exit to up->two, down->one nav = dialogEnd.navigation; nav.mode = Navigation.Mode.Explicit; nav.selectOnDown = dialog1; nav.selectOnUp = dialog2; dialogEnd.navigation = nav; responseOneEnabler.SetActive(true); optionOne.text = d.GetTextOne(); responseTwoEnabler.SetActive(true); optionTwo.text = d.GetTextTwo(); dialog1.Select(); } //no dialog node else if (d.GetNodeOne() == null && d.GetNodeTwo() == null) { dialogDesign.SetActive(false); bye.SetActive(false); byeButton.SetActive(true); //print("set selected to bye button"); dialogEnd = byeButton.GetComponent <Button>(); EventSystem.current.SetSelectedGameObject(byeButton); //set navigation for exit only; Navigation nav = dialogEnd.navigation; nav.mode = Navigation.Mode.None; dialogEnd.navigation = nav; responseOneEnabler.SetActive(false); optionOne.text = d.GetTextOne(); responseTwoEnabler.SetActive(false); optionTwo.text = d.GetTextTwo(); dialogEnd.Select(); } /* Extra: * check each options requirements, and enable invalids accordingly */ }
/// <summary> /// Adds the nodes to show the dialogue view and make the player unable to move at the start of a dialogue /// </summary> /// <param name="next">The dialogue to follow the setup</param> private static DialogueNode DialogueStartCap(DialogueNode next) { return(new DialogueVisibleSelf(true, new DialogueCanPlayerMove(false, next))); }
public DialogueEdge(DialogueNode from, DialogueNode to) { this.to = to; this.from = from; }
public void UpdateStartDialogueNode(DialogueNode node) { currentDialogue.SetStartDialogueNode(node); }
public void AddNode(DialogueNode n) { nodeList.Add (n); }
public void Hide() { CurrentNode = null; show = false; }
void Start() { dm = gameObject.GetComponent<DialogueManager>(); db = GlobalVars.database; show = false; CurrentNode = null; TextBox = new Rect(0, Screen.height / 4, Screen.width, Screen.height / 2); NextBox = new Rect(0, Screen.height / 4 + 64, 64, 32); ChoiceBox = new Rect(0, Screen.height / 4 + 32, 256, 32); ChoiceStartY = Screen.height / 4; }
void Update() { opendoor.gameObjectForOpen = null; Using1.gameObjectForShader = null; Switch.chosenGameObject = null; ActiveObject.chosenGameObject = null; OnDoor.chosenGameObject = null; ActivateScript.chosenGameObject = null; OnChose.chosenGameObject = null; ObjectClicker.chosenGameObject = null; Vector3 Direction = RaycastS.TransformDirection(Vector3.forward); if (Physics.Raycast(RaycastS.position, Direction, out Hit, 1000f)) { if (Hit.collider.material.staticFriction == 0.2f) { //Using1 usingScript = Hit.collider.gameObject.GetComponent<Using1>(); //if (usingScript) //{ // Using1.gameObjectForShader = Hit.collider.gameObject; //} opendoor opendoorScript = Hit.collider.gameObject.GetComponent <opendoor>(); if (opendoorScript) { opendoor.gameObjectForOpen = Hit.collider.gameObject; } Switch switchScript = Hit.collider.gameObject.GetComponent <Switch>(); if (switchScript) { Switch.chosenGameObject = Hit.collider.gameObject; } } ActiveObject activeObjectScript = Hit.collider.gameObject.GetComponent <ActiveObject>(); if (activeObjectScript) { ActiveObject.chosenGameObject = Hit.collider.gameObject; } OnDoor onDoorScript = Hit.collider.gameObject.GetComponent <OnDoor>(); if (onDoorScript) { OnDoor.chosenGameObject = Hit.collider.gameObject; } OnChose onChoseScript = Hit.collider.gameObject.GetComponent <OnChose>(); if (onChoseScript) { OnChose.chosenGameObject = Hit.collider.gameObject; } ObjectClicker onClikerScript = Hit.collider.gameObject.GetComponent <ObjectClicker>(); if (onClikerScript) { ObjectClicker.chosenGameObject = Hit.collider.gameObject; } ActivateScript activateScript = Hit.collider.gameObject.GetComponent <ActivateScript>(); if (activateScript) { ActivateScript.chosenGameObject = Hit.collider.gameObject; } } // ManageTaskDialog(); //if (Input.GetMouseButtonDown(0)) //left //{ // eProject.CallServerMethod_DoAction("1e106acb-e6d3-41f5-865e-4eafb8b329d5", "c176dc43-0a07-4ae7-ba40-556735982901", 1); //} if (Input.GetKeyDown(KeyCode.LeftControl)) { //Cursor.visible = !Cursor.visible; //if(Cursor.lockState == CursorLockMode.None) // Cursor.lockState = CursorLockMode.Locked; //else if (Cursor.lockState == CursorLockMode.Locked) // Cursor.lockState = CursorLockMode.None; //MouseLook scriptMouseLook = gameObject.GetComponent<MouseLook>(); //scriptMouseLook.enabled = !(scriptMouseLook.enabled); MouseLook scriptMouseLook = gameObject.GetComponent <MouseLook>(); if (Cursor.visible == true) { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; scriptMouseLook.enabled = true; } else { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; scriptMouseLook.enabled = false; } } if (Input.GetKeyDown(KeyCode.L)) { gameObjectLight.SetActive(!gameObjectLight.activeSelf); //var listener = new UnityEventListener //{ // EventType = "keyDown", // IdObject = Guid.Empty, // KeyCode = "L" //}; //listener.SendEvent(); GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent <UnityApiScript>(); JsonParametersRotateGameObject jsonParametersRotateGameObject = new JsonParametersRotateGameObject { ObjectName = "Door_Дверь РУВН", Angle = new Vector3(0, 20, 0), IsSpecific = true }; string json = JsonUtility.ToJson(jsonParametersRotateGameObject); unityApiScript.RotateGameObject(json); //List<JsonButton> btns = new List<JsonButton>(); //for (int i=0; i<5; i++) //{ // JsonButton jsonButton = new JsonButton // { // Name = "Команда № " + i.ToString(), // Value = i // }; // btns.Add(jsonButton); //} //unityApiScript.CreateDialog(btns); List <CodeValuePair> codeValuePairs = new List <CodeValuePair>(); List <int> codes = new List <int>(); List <string> values = new List <string>(); Dictionary <int, string> keyValuePairs = new Dictionary <int, string>(); for (int i = 0; i < 5; i++) { int key = i; string value = "Команда № " + i.ToString(); keyValuePairs.Add(key, value); codeValuePairs.Add(new CodeValuePair { Code = key, Value = value }); codes.Add(key); values.Add(value); } DialogData jsonDialog = new DialogData { DialogCode = 1, DialogTitle = "Сумка с причиндалами", // KeyValuePairs = keyValuePairs, // CodeValuePairs = codeValuePairs Codes = codes, Values = values }; string strJsonDialog = JsonUtility.ToJson(jsonDialog); unityApiScript.CreateDialog(strJsonDialog); } if (Input.GetKeyDown(KeyCode.O)) { //GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); //UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent<UnityApiScript>(); //JsonParametersRotateGameObject jsonParametersRotateGameObject = new JsonParametersRotateGameObject //{ // ObjectName = "Door_Дверь РУВН", // Angle = 135f, // IsSpecific = true //}; //string json = JsonUtility.ToJson(jsonParametersRotateGameObject); //unityApiScript.RotateGameObject(json); GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent <UnityApiScript>(); JsonParametersLightGameObject jsonParametersLightGameObject = new JsonParametersLightGameObject { ObjectName = "Твердое тело1 818", IsLight = true }; string json1 = JsonUtility.ToJson(jsonParametersLightGameObject); unityApiScript.LightGameObject(json1); } if (Input.GetKeyDown(KeyCode.P)) { //GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); //UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent<UnityApiScript>(); //JsonParametersRotateGameObject jsonParametersRotateGameObject = new JsonParametersRotateGameObject //{ // ObjectName = "Door_Дверь РУВН", // Angle = 135f, // IsSpecific = true //}; //string json = JsonUtility.ToJson(jsonParametersRotateGameObject); //unityApiScript.RotateGameObject(json); //GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); //UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent<UnityApiScript>(); //JsonParametersLightGameObject jsonParametersLightGameObject = new JsonParametersLightGameObject //{ // ObjectName = "Твердое тело1 818", // IsLight = false //}; //string json1 = JsonUtility.ToJson(jsonParametersLightGameObject); //unityApiScript.LightGameObject(json1); GameObject AssetManager = GameObject.Find("AssetManager"); NonCachingLoadExample NonCachingLoadExample = AssetManager.GetComponent <NonCachingLoadExample>(); AddAssetParameter addAssetParameter = new AddAssetParameter { bundleURL = "D:/Training3dProjects/Training_v7/Assets/AssetBundles/cubeasset", assetName = "D:/Training3dProjects/Training_v7/Assets/Scenes/Resources_2018.12.26/Cube.prefab"//"A20", }; }; string json1 = JsonUtility.ToJson(addAssetParameter); NonCachingLoadExample.LoadAsset(json1); } if (Input.GetKeyDown(KeyCode.G)) { //GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); //UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent<UnityApiScript>(); //JsonParametersRotateGameObject jsonParametersRotateGameObject = new JsonParametersRotateGameObject //{ // ObjectName = "Door_Дверь РУВН", // Angle = 135f, // IsSpecific = true //}; //string json = JsonUtility.ToJson(jsonParametersRotateGameObject); //unityApiScript.RotateGameObject(json); GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); UnityApiScript unityApiScript = gameObjectUnityApi.GetComponent <UnityApiScript>(); JsonParametersPositionGameObject jsonParametersPositionGameObject = new JsonParametersPositionGameObject { ObjectName = "Твердое тело1 88", Position = new Vector3(0.5f, 0f, 0f), SetNew = false }; string json = JsonUtility.ToJson(jsonParametersPositionGameObject); unityApiScript.ChangePositionObject(json); } if (Input.GetKeyDown(KeyCode.J)) { MouseLook scriptMouseLook = gameObject.GetComponent <MouseLook>(); Zoom scriptZoom = GameObject.Find("Player").GetComponent <Zoom>(); GameObject mainCamera = GameObject.Find("Main Camera"); Dialogue dialogueScript = mainCamera.GetComponent <Dialogue>(); if (dialogueScript.ShowDialogue == true) { //Cursor.visible = false; //Cursor.lockState = CursorLockMode.Locked; scriptMouseLook.enabled = true; scriptZoom.enabled = true; } else { // Cursor.visible = true; // Cursor.lockState = CursorLockMode.None; scriptMouseLook.enabled = false; scriptZoom.enabled = false; } if (dialogueScript.ShowDialogue == true) { dialogueScript.ShowDialogue = false; } else { DialogueNode node0 = new DialogueNode(); node0.NpcText = "Я: -Здравствуйте, диспетчерская?\n"; node0.NpcText += "Диспетчер: -Здравствуйте, диспетчер Иванов, слушаю."; Answer ans0_1 = new Answer { Text = "Я: - Прошу снять напряжение с КТП-10/0,4 с номером 86732. Потребители уведомлены о снятии напряжения.\nДиспетчер: - Снимаю напряжение с КТП-10/0,4 с номером 86732.", ToNode = 0, SpeakEnd = true, ActionRef = "e9477766-93dc-497d-a7e0-91ab73dcaab5", ElementRef = Guid.Empty.ToString(), InventoryItemRef = "41a454ad-e7cb-4785-a4d5-d969f42abb81" }; Answer ans0_2 = new Answer { Text = "Я: - Вы сняли напряжение?\nДиспетчер: - Да, напряжение с КТП-10/0,4 снято.", ToNode = 0, SpeakEnd = true, ActionRef = "e474abb8-b273-48ec-b138-131c28ca0826", ElementRef = Guid.Empty.ToString(), InventoryItemRef = "41a454ad-e7cb-4785-a4d5-d969f42abb81" }; Answer ans0_3 = new Answer { Text = "Я: - Прошу подать напряжение на КТП 10/0,4. с номером 86732 \"Считаю, КТП 10/0.4 под напряжением\"\nДиспетчер: - Напряжение подано", ToNode = 0, SpeakEnd = true, ActionRef = "e20b60e8-b7a1-4ed0-ba4b-c315c0d20149", ElementRef = Guid.Empty.ToString(), InventoryItemRef = "41a454ad-e7cb-4785-a4d5-d969f42abb81" }; Answer ans0_4 = new Answer { Text = "Я: - Прошу снять напряжение с КТП-10/0,4 с номером 843432. Потребители уведомлены о снятии напряжения.\nДиспетчер: - Снимаю напряжение с КТП-10/0,4 с номером 843432.", ToNode = 0, SpeakEnd = true, ActionRef = "06a9e850-b562-4209-b98d-765fa8b7d071", ElementRef = "", InventoryItemRef = "41a454ad-e7cb-4785-a4d5-d969f42abb81" }; Answer ans0_5 = new Answer { Text = "Я: - Прошу подать напряжение на КТП-10/0,4 с номером 321455. \"Считаю, КТП 10 / 0.4 под напряжением\"\nДиспетчер: - Напряжение подано", ToNode = 0, SpeakEnd = true, ActionRef = "604640b3-f525-4e48-a051-8e008d9dd286", ElementRef = "", InventoryItemRef = "41a454ad-e7cb-4785-a4d5-d969f42abb81" }; node0.PlayerAnswer = new Answer[] { ans0_1, ans0_2, ans0_3, ans0_4, ans0_5 }; //DialogueNode node1 = new DialogueNode(); //node1.NpcText = "Выполняю снятие напряжения с КТП-10/0,4."; //node1.PlayerAnswer = new Answer[] { ans0_2, ans0_3, ans0_4, ans0_5 }; //DialogueNode node2 = new DialogueNode(); //node2.NpcText = "Подтверждаю о снятии напряжения с КТП-10/0,4."; //node2.PlayerAnswer = new Answer[] { ans0_3, ans0_4, ans0_5 }; //DialogueNode node3 = new DialogueNode(); //node3.NpcText = "Подано напряжение на КТП 10/0,4."; //node3.PlayerAnswer = new Answer[] { ans0_5 }; dialogueScript._currentNode = 0; dialogueScript.node = new DialogueNode[] { node0 }; dialogueScript.ShowDialogue = true; } } //if (Input.GetKeyDown(KeyCode.Space)) //{ // MouseLook scriptMouseLook = gameObject.GetComponent<MouseLook>(); // if (Cursor.visible == true) // { // Cursor.visible = false; // Cursor.lockState = CursorLockMode.Locked; // scriptMouseLook.enabled = true; // } // else // { // Cursor.visible = true; // Cursor.lockState = CursorLockMode.None; // scriptMouseLook.enabled = false; // } // // // GameObject gameObjectUnityApi = GameObject.Find("UnityAPI"); // Actions unityApiScript = gameObjectUnityApi.GetComponent<Actions>(); // Actions.show = !Actions.show; // //} }
public void TriggerNextDialogue(int choice) { currentNode = currentNode.choices[choice]; StartCoroutine(FadeIn()); }
public void TriggerNextDialogue(DialogueNode node) { currentNode = node; StartCoroutine(FadeIn()); }
private Port GeneratePort(DialogueNode node, Direction portDirection, Port.Capacity capacity = Port.Capacity.Single) { return(node.InstantiatePort(Orientation.Horizontal, portDirection, capacity, typeof(float))); }
private void GotoNode() { if(State == DialogueState.IN_TOPIC) { if(NodeCurrentId < NodeList.Count) { NodeCurrent = NodeList[NodeCurrentId]; switch(NodeCurrent.GetType()) { case DialogueNode.NodeType.Action: HandleActionNode(); break; case DialogueNode.NodeType.Sprite: HandleSpriteNode(); break; default: UpdateGUI(); break; } } else { // if we reach end of topic, go back to the topic list ReturnToTopicList(); } } }
public void SetLinkingNode(DialogueNode node) { LinkingNode = Optional <DialogueNode> .Some(node); }
private void AddNode(DialogueNode newNode) { nodes.Add(newNode); OnValidate(); }
/// <summary> /// Adds a new node to this dialogue sequence. /// </summary> /// <returns><c>true</c>, if node was added, <c>false</c> otherwise.</returns> /// <param name="node">The node to add.</param> public bool AddNode(DialogueNode node) { nodes.Add(node); return true; }
public DialogueVisibleSelf(bool newVisibility, DialogueNode nextNode = null) : base(nextNode) { this.newVisibility = newVisibility; }
public void ShowNode(DialogueNode node, Inventory inventory, FlagSet flag_set) { this.dialogue_controller.Show(node, inventory, flag_set); EnableInputs(); }
public void RefreshDialogue(string newNodeID, bool showResponse) { //if loading a new node, first create a dialogue entry for it and push into //the stack. if (newNodeID != "") { //create dialogue entry //Debug.Log("new node ID " + newNodeID); DialogueNode node = GameManager.Inst.DBManager.DBHandlerDialogue.GetDialogueNode(newNodeID); if (showResponse) { DialogueResponse response = EvaluateResponse(node.Responses); if (response != null) { DialogueEntry entry = CreateDialogueEntry(GetSpeakerName(), ParseDialogueText(response.Text), false); _entries.Push(entry); //check if response has an event if (response.Events != null && response.Events.Count > 0) { foreach (string e in response.Events) { if (GameManager.Inst.QuestManager.Scripts.ContainsKey(e)) { StoryEventScript script = GameManager.Inst.QuestManager.Scripts[e]; script.Trigger(new object[] {}); } } } } } //create dialogue options relevant to this node foreach (Topic option in node.Options) { if (EvaluateTopicConditions(option.Conditions)) { DialogueOptionEntry optionEntry = new DialogueOptionEntry(); GameObject o = GameObject.Instantiate(Resources.Load("TopicEntry")) as GameObject; optionEntry.Text = o.GetComponent <UILabel>(); optionEntry.Text.text = option.Title; TopicReference reference = o.GetComponent <TopicReference>(); reference.Topic = option; UIButton button = o.GetComponent <UIButton>(); button.onClick.Add(new EventDelegate(this, "OnSelectTopic")); _options.Add(optionEntry); } } } //create topics entry Character target = GameManager.Inst.PlayerControl.SelectedPC.MyAI.BlackBoard.InteractTarget; List <Topic> topics = GameManager.Inst.DBManager.DBHandlerDialogue.GetNPCTopics(target, null); foreach (Topic topic in topics) { //if we are not at root node then don't show info topics if (topic.Type == TopicType.Info && _currentNodeID != _rootNode) { continue; } //if topic is not known to player, don't show it if (topic.Type == TopicType.Info && !GameManager.Inst.PlayerProgress.IsTopicDiscovered(topic.ID)) { continue; } TopicEntry entry = new TopicEntry(); GameObject o = GameObject.Instantiate(Resources.Load("TopicEntry")) as GameObject; entry.Text = o.GetComponent <UILabel>(); entry.Text.text = topic.Title; TopicReference reference = o.GetComponent <TopicReference>(); reference.Topic = topic; UIButton button = o.GetComponent <UIButton>(); button.onClick.Add(new EventDelegate(this, "OnSelectTopic")); BoxCollider2D collider = o.GetComponent <BoxCollider2D>(); collider.size = new Vector2(collider.size.x, 27); entry.Type = topic.Type; _topics.Add(entry); } //now make a copy of the stack, and start popping entries out of it, and arrange them under the dialog panel Stack <DialogueEntry> copy = new Stack <DialogueEntry>(_entries.Reverse()); float currentY = -260; _totalHeight = 0; int i = 0; while (copy.Count > 0) { DialogueEntry entry = copy.Pop(); entry.SpeakerName.transform.parent = DialogueEntryAnchor.transform; entry.SpeakerName.MakePixelPerfect(); entry.Text.transform.parent = DialogueEntryAnchor.transform; entry.Text.MakePixelPerfect(); float height = Mathf.Max(entry.SpeakerName.height * 1f, entry.Text.height * 1f); entry.SpeakerName.transform.localPosition = new Vector3(-150, currentY + height, 0); entry.Text.transform.localPosition = new Vector3(22, currentY + height, 0); currentY = currentY + height + 15; _totalHeight += (height + 15); if (_totalHeight < 400) { DialogueEntryAnchor.localPosition = new Vector3(-210, 0 - _totalHeight, 0); _dialogueAnchorTarget = new Vector3(-210, 175 - _totalHeight, 0); } else { DialogueEntryAnchor.localPosition = new Vector3(-210, -220, 0); _dialogueAnchorTarget = new Vector3(-210, -175, 0); } i++; } //now re-add collider to fix collider size NGUITools.AddWidgetCollider(DialogueScroll.gameObject); /* * if(_intro != null) * { * _intro.transform.parent = DialogueEntryAnchor.transform; * _intro.MakePixelPerfect(); * _intro.transform.localPosition = new Vector3(-150, currentY + _intro.height, 0); * } */ //arrange topic entries currentY = 200; TopicScroll.ResetPosition(); foreach (TopicEntry entry in _topics) { entry.Text.transform.parent = TopicAnchor.transform; entry.Text.MakePixelPerfect(); entry.Text.transform.localPosition = new Vector3(0, currentY, 0); currentY = currentY - entry.Text.height; if (entry.Text.text == "Goodbye") { currentY = currentY - 15; } if (entry.Type != TopicType.Info) { entry.Text.color = new Color(0.5f, 0.5f, 0.8f); } } //now re-add collider to fix collider size //NGUITools.AddWidgetCollider(TopicScroll.gameObject, false); float currentX = -128; foreach (DialogueOptionEntry entry in _options) { entry.Text.transform.parent = DialogueOptionScroll.transform; entry.Text.MakePixelPerfect(); entry.Text.width = entry.Text.text.Length * 15; entry.Text.transform.localPosition = new Vector3(currentX, 78, 0); BoxCollider2D collider = entry.Text.GetComponent <BoxCollider2D>(); collider.size = new Vector2(collider.size.x, 27); currentX = currentX + entry.Text.width + 20; } }
public void SetTo(DialogueNode t) { this.to = t; }
// Update is called once per frame void OnGUI() { bool add = false; if (GUILayout.Button("Export Nodes")) { DialogueController.SaveDictionary(); } if (GUILayout.Button("Add Node")) { add = true; } _key = EditorGUILayout.TextField("Node Key:", _key); _text = EditorGUILayout.TextField("Node Text:", _text); _responseText = EditorGUILayout.TextField("Node Response Text:", _responseText); _isMemory = EditorGUILayout.Toggle("Is Memory Node:", _isMemory); _amountOfResponseNodes = EditorGUILayout.IntField("Amount of Response Nodes:", _amountOfResponseNodes); if (_responseNodes != null) { if (_responseNodes.Count > 0) { List <string> oldNodes = new List <string>(); oldNodes = _responseNodes; _responseNodes = new List <string>(); for (int i = 0; i < _amountOfResponseNodes; i++) { _responseNodes.Add(oldNodes[i]); } } else { for (int i = 0; i < _amountOfResponseNodes; i++) { _responseNodes.Add(""); } } } else { _responseNodes = new List <string>(); for (int i = 0; i < _amountOfResponseNodes; i++) { _responseNodes.Add(""); } } for (int i = 0; i < _responseNodes.Count; i++) { _responseNodes[i] = EditorGUILayout.TextField("Node Response " + i, _responseNodes[i]); } if (add) { DialogueNode node = new DialogueNode(_key, _text, _responseText, _responseNodes, _isMemory); DialogueController.AddDialogueNode(node); _amountOfResponseNodes = 0; _isMemory = false; _key = ""; _responseText = ""; _text = ""; } }
public static LinkDialogueNodes Create(DialogueNode node) { return(new LinkDialogueNodes(node)); }
public void GetNodeFunction(List <NodePort> _ports) { //cannot find a way to use a switch, so we'll have to stick with a bunch of if statements :notlikethis: foreach (NodePort _nodePort in _ports) { XNode.Node _node = _nodePort.node; if (_node.GetType() == typeof(DialogueNode)) { dialoguePanel.SetActive(true); currentDialogue = _node as DialogueNode; ShowDialogue(currentDialogue); return; //do NOT grab the node after this, and wait for the player to advance the dialogue } if (_node.GetType() == typeof(EndSceneNode)) { EndCutscene(); return; } if (_node is MovementNode movementNode) { StartCoroutine(movementNode.CharacterMovement()); } if (_node.GetType() == typeof(CloseDialogue)) { dialoguePanel.SetActive(false); speakerPanel.SetActive(false); } if (_node.GetType() == typeof(CG)) { CG scopedCGNode = _node as CG; showCG(_node as CG); if (scopedCGNode.waitForInput) { currentCGNode = scopedCGNode; dialoguePanel.gameObject.SetActive(false); _charactersInScene.SetActive(false); CGWaitingForInput = true; return; } } if (_node.GetType() == typeof(SetSpriteNode)) { SetImage(_node as SetSpriteNode); } if (_node.GetType() == typeof(CGHide)) { _cgGraphic.enabled = false; } if (_node.GetType() == typeof(WaitFor)) { WaitFor _waitForNode = _node as WaitFor; StartCoroutine(WaitToAdvance(_waitForNode)); //do not get next node automatically return; } if (_node.GetType() == typeof(Choices)) { ChoicePanel.SetActive(true); nodeOptions = new List <Node>(); int listIndex = 0; Choices _choiceNode = _node as Choices; NodePort _choicePort = _choiceNode.GetOutputPort("output"); List <NodePort> _nodePorts = _choicePort.GetConnections(); foreach (NodePort _NP in _nodePorts) { nodeOptions.Add(_NP.node); Button _newOption = Instantiate(choiceButton) as Button; _newOption.transform.SetParent(ChoicePanel.transform); listIndex++;//on this button it where on the list it is, using this //ChoiceOptionHolder _holder = _newOption.GetComponent<ChoiceOptionHolder>(); OptionNode optionNode = _NP.node as OptionNode; _newOption.GetComponentInChildren <Text>().text = optionNode.optionText; _newOption.GetComponent <ChoiceOptionHolder>().node = _NP.node; // _holder.node = _NP.node; // _holder.indexOfOptions = listIndex; } return; //do not load next node, since we want the player input to decide the branch to go down } //get next node(s) NodePort _port = _node.GetOutputPort("output"); if (_port.IsConnected) { GetNodeFunction(_port.GetConnections()); } } }
// Use this for initialization void Start() { isTalking = false; playerColliding = false; NPCstate = 1; Parser = new XmlParser(xml); dialogueGraph = (DialogueGraph)Parser.GetGraph(); currentNode = GetStartNode(NPCstate); m = new GameConditionManager(); }
public void AddMessage(string charId, DialogueNode dialogueNode, MessageType mode, string dialogId) { DialogueNode tempNode; TextMes tempSms; switch (mode) { case MessageType.Sms: TextMes tempMess = new TextMes(); tempMess.node = dialogueNode; tempMess.dialogId = dialogId; if (!textMessages.ContainsKey(charId)) { textMessages.Add(charId, new Queue <DialogueNode>()); textMessages[charId].Enqueue(dialogueNode); TextMessages.Add(charId, new Queue <TextMes>()); TextMessages[charId].Enqueue(tempMess); } else { Queue <DialogueNode> temp = new Queue <DialogueNode>(textMessages[charId].Reverse()); Queue <TextMes> tempText = new Queue <TextMes>(TextMessages[charId].Reverse()); if (temp.Count > 0) { tempNode = temp.Peek(); tempSms = tempText.Peek(); if (tempNode.Id != dialogueNode.Id) { textMessages[charId].Enqueue(dialogueNode); TextMessages[charId].Enqueue(tempMess); } } else { textMessages[charId].Enqueue(dialogueNode); TextMessages[charId].Enqueue(tempMess); } } break; case MessageType.Email: Queue <MessNode> tempQ = new Queue <MessNode>(emailMessages.Reverse()); if (tempQ.Count > 0) { tempNode = tempQ.Peek().node; if (tempNode.Id != dialogueNode.Id) { MessNode mes = new MessNode() { node = dialogueNode, date = CoreController.TimeModule.GetDate() }; emailMessages.Enqueue(mes); } } else { MessNode mes = new MessNode() { node = dialogueNode, date = CoreController.TimeModule.GetDate() }; emailMessages.Enqueue(mes); } break; default: break; } }
public void ExecuteNode() { DialogueNode node = DialogueSystem.GET_NODES()[nodeNumber]; node.ChangeRequestValue(node.GetRunValue(), true); }
private DialogueNode BuildDialogueNode(DialogueEntry entry, Link originLink, int level, List<DialogueEntry> visited) { if (entry == null) return null; bool wasEntryAlreadyVisited = visited.Contains(entry); if (!wasEntryAlreadyVisited) visited.Add(entry); // Create this node: float indent = DialogueEntryIndent * level; bool isLeaf = (entry.outgoingLinks.Count == 0); bool hasFoldout = !(isLeaf || wasEntryAlreadyVisited); GUIStyle guiStyle = wasEntryAlreadyVisited ? grayGUIStyle : isLeaf ? GetDialogueEntryLeafStyle(entry) : GetDialogueEntryStyle(entry); DialogueNode node = new DialogueNode(entry, originLink, guiStyle, indent, !wasEntryAlreadyVisited, hasFoldout); if (!dialogueEntryFoldouts.ContainsKey(entry.id)) dialogueEntryFoldouts[entry.id] = true; // Add children: if (!wasEntryAlreadyVisited) { foreach (Link link in entry.outgoingLinks) { if (link.destinationConversationID == currentConversation.id) { // Only show connection if within same conv. node.children.Add(BuildDialogueNode(currentConversation.GetDialogueEntry(link.destinationDialogueID), link, level + 1, visited)); } } } return node; }
public static void DeleteNode(DialogueNode node) { NodeDictionary.Remove(NodeDictionary.Where(pair => pair.Value == node).First().Key); }
void NextOption(DialogueNode nodeToSpawn) { if (currentNode != null && currentNode.playerDead) { GameObject deadAnim = Instantiate(PlayerDeadAnim); deadAnim.GetComponent<SceneStartEnd>().nextScene = currentScene; return; } currentNode = nodeToSpawn; if (currentSpawnedDialogue != null) { Destroy(currentSpawnedDialogue); } if (currentNode.pauseBefore) { currentNode.pauseBefore = false; dialogueInProgress = false; return; } if (currentNode.audio != null) { AudioSource myClip = null; if (currentNode.addToCanvas) { myClip = GameObject.Find("Canvas").AddComponent<AudioSource>(); myClip.clip = Resources.Load<AudioClip>(currentNode.audio); myClip.playOnAwake = true; myClip.Play(); } } if (currentNode.nextNode.Count == 0) { GameObject.Find("Fade").GetComponent<SceneStartEnd>().FadeOut(); this.enabled = false; return; } if (nodeToSpawn.nextNode.Count == 1 || nodeToSpawn.nextNode.Count == 0) { currentSpawnedDialogue = Instantiate(DialogueSingle) as GameObject; currentTimer = nodeToSpawn.time; timerOn = true; } else { currentSpawnedDialogue = Instantiate(DialogueMultiple) as GameObject; Button[] buttons = currentSpawnedDialogue.GetComponentsInChildren<Button>(); for (int i = 0; i < buttons.Length; i++) { buttons[i].GetComponentInChildren<Text>().text = currentNode.nextNode[i].dialogueText; } buttons[0].onClick.AddListener(delegate () { NextOption(currentNode.nextNode[0].nextNode[0]); }); buttons[1].onClick.AddListener(delegate () { NextOption(currentNode.nextNode[1].nextNode[0]); }); buttons[2].onClick.AddListener(delegate () { NextOption(currentNode.nextNode[2].nextNode[0]); }); } if (currentNode.image != null) { Image img = currentSpawnedDialogue.GetComponentsInChildren<Image>()[1]; img.sprite = Resources.Load<Sprite>(currentNode.image); Color c = img.color; c.a = 1.0f; img.color = c; } if (currentNode.audio != null) { AudioSource myClip = null; if (!currentNode.addToCanvas) { myClip = currentSpawnedDialogue.AddComponent<AudioSource>(); myClip.clip = Resources.Load<AudioClip>(currentNode.audio); myClip.playOnAwake = true; myClip.Play(); } } if (currentNode.sceneChange != null) { Camera.main.GetComponentInChildren<SpriteRenderer>().sprite = Resources.Load<Sprite>(currentNode.sceneChange); } currentSpawnedDialogue.transform.SetParent(canvas.transform); currentSpawnedDialogue.GetComponent<RectTransform>().offsetMax = new Vector2(-200f, 150f); }
public override bool CanBeFollowedByNode(DialogueNode node) { return(m_NextNode == node); }
public DialogueGraph ConvoGraph() { s.Start (); DialogueGraph convoGraph = new DialogueGraph(); XmlNodeList dialogues = xml.DocumentElement.SelectNodes ("/conversation/dialogue"); /* * Loops through all the dialogue nodes first without * processing any replies, this is because to be able * to link the player questions to corresponding replies * the dialogues need to be accessible in the graph before * they can be linked to. */ foreach (XmlNode dialogueNode in dialogues) { DialogueNode dNode = new DialogueNode(); if(dialogueNode.Attributes["actorname"].Value != null) { dNode.SetActorName(dialogueNode.Attributes["actorname"].Value); } if(dialogueNode.Attributes["actordialogue"].Value !=null) { dNode.SetDialogue(dialogueNode.Attributes["actordialogue"].Value); } if(dialogueNode.Attributes["id"].Value != null) { dNode.SetID (int.Parse (dialogueNode.Attributes["id"].Value)); } if(dialogueNode.Attributes["state"].Value != null) { dNode.SetState(int.Parse(dialogueNode.Attributes["state"].Value)); } convoGraph.AddNode(dNode); } /* * Loops back through the dialogue nodes only * looking at the child node replies */ foreach(XmlNode dialogueNode in dialogues) { foreach (XmlNode childNode in dialogueNode.ChildNodes) { if(childNode.Name.ToUpper().Equals("REPLIES")) { foreach (XmlNode replyNode in childNode.ChildNodes) { DialogueNode repNode = new DialogueNode(); if(replyNode.Attributes["text"].Value != null) { repNode.SetDialogue(replyNode.Attributes["text"].Value); } if(replyNode.Attributes["condition"].Value !=null) { repNode.SetCondition(replyNode.Attributes["condition"].Value); } if(replyNode.Attributes["goto"].Value != null) { if(replyNode.Attributes["goto"].Value.Equals ("-9999")) { //Ends the Conversation UnityEngine.Debug.Log("CONVO OVER"); if(replyNode.Attributes["nextstate"].Value !=null) { repNode.SetNextState(int.Parse (replyNode.Attributes["nextstate"].Value)); } } else { int id = int.Parse(replyNode.Attributes["goto"].Value); convoGraph.AddEdge(repNode, convoGraph.FindNode(id)); } } convoGraph.AddNode (repNode); convoGraph.AddEdge (convoGraph.FindNode(int.Parse(dialogueNode.Attributes["id"].Value)),repNode); UnityEngine.Debug.Log(dialogueNode.Attributes["id"].Value + " to " + repNode.GetDialogue()); } } } } s.Stop(); UnityEngine.Debug.Log("Time Elapsed for " + convoGraph.GetNodeList()[0].GetActorName() + ": " + s.Elapsed + "\nTotal Nodes: " + convoGraph.GetNodeList().Count.ToString()); return convoGraph; }
public void AddEdge(DialogueNode from, DialogueNode to) { from.GetNeighbors().Add(new DialogueEdge(from, to)); }
//Marca el nodo como leído, y comprueba las propiedades del nodo actual //tipo = 0: El dialogo actual está situado en una intro // 1: El dialogo actual está situado en un mensaje que no forma parte de ningún temamensaje // 2: El dialogo actual está situado en un mensaje que forma parte de un temamensaje public void MarcaDialogueNodeComoLeido(int tipo, int posTema, ref int posDialogo, DialogueNode node) { //Si el nodo no ha sido recorrido nunca, ejecutamos las funciones if(node.DevuelveRecorrido() != true) { //Dependiendo del tipo, comprobamos una lista u otra switch(tipo) { case 0: //Si está marcado que el dialogo se destruye, activamos la autodestrucción de este if(node.destruido) intros [posDialogo].ActivarAutodestruye(); break; case 1: //Si está marcado que el dialogo se destruye, activamos la autodestrucción de este if(node.destruido) mensajes [posDialogo].ActivarAutodestruye(); break; case 2: //Si está marcado que el dialogo se destruye, activamos la autodestrucción de este if(node.destruido) temaMensajes[posTema].mensajes[posDialogo].ActivarAutodestruye(); break; } //Marcamos el nodo como recorrido y comprobamos las funciones del nodo actual node.MarcarRecorrido(); ComprobarPropiedadesNodo(tipo, posTema, ref posDialogo, node); } }
private bool CanStartNode(DialogueNode node) { return(m_CurrentNode == null || node == null || m_CurrentNode.CanBeFollowedByNode(node)); }
public DialogueAcceptQuest(int questID, DialogueNode nextNode = null) : base(nextNode) { this.questID = questID; }
private void BuildDialogueTree() { List<DialogueEntry> visited = new List<DialogueEntry>(); dialogueTree = BuildDialogueNode(startEntry, null, 0, visited); RecordOrphans(visited); BuildLanguageListFromConversation(); }
IEnumerator WaitForKeyDownStart() { ui.ShowTextHolder(); while (true) { if (Input.GetKeyDown(KeyCode.Return)) { if (allowingInput) { if (toSay != null && toSay.updateFlagName != null && toSay.updateFlagName != "") { party.flags[toSay.updateFlagName] = toSay.updateFlagValue; } if (toSay != null && toSay.initiateBattle) { ui.HideTextHolder(); owner.ResetLoc(toSay.newResetLocation); SceneMgmt.SetToFight(toSay.encounterPrefab, toSay.arenaPrefab, SceneManager.GetActiveScene().name, GameObject.Find("Player").transform.position); //SceneMgmt.LoadScene("Battle"); yield break; } if (toSay != null && toSay.endBranch) { ui.HideTextHolder(); owner.ResetLoc(toSay.newResetLocation); if (toSay.destroyAfterDialogue) { GameObject.Destroy(owner.gameObject); } yield break; } toSay = owner.GetNextNode(); if (toSay != null) { if (toSay.togglePartyMember) { party.GetUnitStats(toSay.partyMemberToToggle).available = !party.GetUnitStats(toSay.partyMemberToToggle).available; } if (toSay.mustHaveFlagToContinue != null && toSay.mustHaveFlagToContinue != "") { if (!party.flags[toSay.mustHaveFlagToContinue]) { ui.HideTextHolder(); owner.ResetLoc(toSay.newResetLocation); yield break; } } if (toSay.mustNotHaveFlagToContinue != null && toSay.mustNotHaveFlagToContinue != "") { if (party.flags[toSay.mustNotHaveFlagToContinue]) { ui.HideTextHolder(); owner.ResetLoc(toSay.newResetLocation); yield break; } } if (toSay.showChoice) { Advance(); ui.SetChoiceText(toSay.yesText, toSay.noText); ui.ShowChoiceHolder(); allowingInput = false; } else { Advance(); } } else { ui.HideTextHolder(); owner.ResetLoc(toSay.newResetLocation); yield break; } } } yield return(null); } }
private void init() { // Create a node and populate the head value DialogueNode currentNode = new DialogueNode(); head = currentNode; // Read in the XML file XmlTextReader reader = new XmlTextReader(path); XmlDocument xml = new XmlDocument(); xml.Load(reader); XmlNodeList sections = xml.SelectNodes("/dialogue/dialogueSection"); DialogueNode prevNode = null; foreach (XmlNode dSection in sections) { if (prevNode != null) { currentNode = new DialogueNode(); if (prevNode.nextNode.Count > 0) { foreach (DialogueNode n in prevNode.nextNode) { n.nextNode[0].nextNode.Add(currentNode); } } else { prevNode.nextNode.Add(currentNode); prevNode.choiceCount = 1; } } currentNode.dialogueText = dSection["text"].InnerText; if (dSection["image"] != null) currentNode.image = dSection["image"].InnerText; if (dSection["audio"] != null) { currentNode.audio = dSection["audio"].InnerText; if (dSection["audio"].Attributes["addTo"] != null) currentNode.addToCanvas = true; } if (dSection["scenechange"] != null) { currentNode.sceneChange = dSection["scenechange"].InnerText; } if (dSection.Attributes["action"] != null && dSection.Attributes["action"].Value == "pause") { currentNode.pauseBefore = true; } if (dSection["options"] != null) { XmlNodeList options = dSection["options"].ChildNodes; foreach(XmlNode option in options) { DialogueNode myOption = new DialogueNode(); myOption.dialogueText = option["text"].InnerText; DialogueNode replyOption = new DialogueNode(); replyOption.dialogueText = option["reply"].InnerText; if (option["reply"].GetAttribute("action") == "die") replyOption.playerDead = true; if (option["image"] != null) replyOption.image = option["image"].InnerText; myOption.nextNode.Add(replyOption); currentNode.choiceCount++; currentNode.nextNode.Add(myOption); } } prevNode = currentNode; } NextOption(head); }
private void DrawDialogueNode( DialogueNode node, Link originLink, ref Link linkToDelete, ref DialogueEntry entryToLinkFrom, ref DialogueEntry entryToLinkTo, ref bool linkToAnotherConversation) { if (node == null) return; // Setup: bool deleted = false; EditorGUILayout.BeginHorizontal(); GUILayout.Label(string.Empty, GUILayout.Width(node.indent)); if (node.isEditable) { // Draw foldout if applicable: if (node.hasFoldout && node.entry != null) { Rect rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(FoldoutRectWidth)); dialogueEntryFoldouts[node.entry.id] = EditorGUI.Foldout(rect, dialogueEntryFoldouts[node.entry.id], string.Empty); } // Draw label/button to edit: if (GUILayout.Button(GetDialogueEntryText(node.entry), node.guiStyle)) { GUIUtility.keyboardControl = 0; currentEntry = (currentEntry != node.entry) ? node.entry : null; ResetLuaWizards(); ResetDialogueTreeCurrentEntryParticipants(); } // Draw delete-node button: GUI.enabled = (originLink != null); deleted = GUILayout.Button(new GUIContent(" ", "Delete entry."), "OL Minus", GUILayout.Width(16)); if (deleted) linkToDelete = originLink; GUI.enabled = true; } else { // Draw uneditable node: EditorGUILayout.LabelField(GetDialogueEntryText(node.entry), node.guiStyle); GUI.enabled = false; GUILayout.Button(" ", "OL Minus", GUILayout.Width(16)); GUI.enabled = true; } EditorGUILayout.EndHorizontal(); // Draw contents if this is the currently-selected entry: if (!deleted && (node.entry == currentEntry) && node.isEditable) { DrawDialogueEntryContents(currentEntry, ref linkToDelete, ref entryToLinkFrom, ref entryToLinkTo, ref linkToAnotherConversation); } // Draw children: if (!deleted && node.hasFoldout && (node.entry != null) && dialogueEntryFoldouts[node.entry.id]) { foreach (var child in node.children) { if (child != null) { DrawDialogueNode(child, child.originLink, ref linkToDelete, ref entryToLinkFrom, ref entryToLinkTo, ref linkToAnotherConversation); } } } }
public DialogueNode GetDialogueNode(string id) { XmlElement node = CurrentDialogXML.GetElementById(id); if(node == null) { return null; } XmlNodeList nodeContent = node.ChildNodes; DialogueNode dialogueNode = new DialogueNode(); foreach(XmlNode nodeItem in nodeContent) { if(nodeItem.Name == "response") { DialogueResponse response = GetDialogueResponse(nodeItem); dialogueNode.Responses.Add(response); } else if(nodeItem.Name == "option") { Topic option = GetDialogueOption(nodeItem); dialogueNode.Options.Add(option); } } return dialogueNode; }
private void ResetDialogueTree() { dialogueTree = null; orphans.Clear(); ResetLanguageList(); }
//Comprobamos las propiedades del nodo recorriendo sus listas //tipo_dialogo = 0: El dialogo actual está situado en una intro // 1: El dialogo actual está situado en un mensaje que no forma parte de ningún temamensaje // 2: El dialogo actual está situado en un mensaje que forma parte de un temamensaje private void ComprobarPropiedadesNodo(int tipoDialogo, int posTema, ref int posDialogo, DialogueNode node) { //Comprueba los grupos del nodo //Se añaden/eliminan los grupos indicados for(int i = 0; i < node.DevuelveNumeroGrupos(); i++) { int IDGrupo = node.grupos[i].DevuelveID(); bool tipo = node.grupos[i].DevuelveTipo(); //Si el tipo es verdadero, cargamos el grupo if(tipo) { CrearGrupo(IDGrupo, tipoDialogo, ref posDialogo); } //Si es falso, destruimos el grupo indicado y las intros/mensajes asignados a él else { EliminarGrupo(IDGrupo, tipoDialogo, posTema, ref posDialogo); } } //Comprueba la lista de intros a añadir for(int i = 0; i < node.DevuelveNumeroIntros(); i++) { int prioridad = node.intros[i].DevuelvePrioridad(); int ID = node.intros[i].DevuelveIDIntro(); int IDInteractuable = node.intros[i].devuelveIDInteractuable(); int IDDialogo = node.intros[i].DevuelveIDDialogo(); Intro intro = Intro.LoadIntro(Manager.rutaIntros + ID.ToString() + ".xml", prioridad); //Si la intro forma parte de un grupo y ese grupo ya ha acabado, no es añadida if(!Manager.instance.GrupoAcabadoExiste(intro.DevuelveIDGrupo())) { //Si nos encontramos en el diálogo el cual queremos añadir una intro if(IDInteractuable == this.IDInteractuable && IDDialogo == this.ID) { //Si estamos en una intro y la prioridad es mayor que la actual, cambiamos el indice de dialogo if(tipoDialogo == 0 && prioridad > intros[posDialogo].DevuelvePrioridad()) { posDialogo++; } AnyadirIntro(intro); } else { Dialogo dialogo = BuscarDialogo(IDInteractuable, IDDialogo); dialogo.AnyadirIntro(intro); dialogo.AddToColaObjetos(); } } } //Comprueba los mensajes a añadir for(int i = 0; i < node.DevuelveNumeroMensajes(); i++) { int ID = node.mensajes[i].DevuelveID(); int IDTema = node.mensajes[i].DevuelveIDTema(); int IDInteractuable = node.mensajes[i].DevuelveIDInteractuable(); int IDDialogo = node.mensajes[i].DevuelveIDDialogo(); Mensaje mensaje = Mensaje.LoadMensaje(Manager.rutaMensajes + ID.ToString() + ".xml"); //Si el mensaje forma parte de un grupo y ese grupo ya ha acabado, no es añadido if(!Manager.instance.GrupoAcabadoExiste(mensaje.DevuelveIDGrupo())) { //Si nos encontramos en el diálogo el cual queremos añadir un mensaje if(IDInteractuable == this.IDInteractuable && IDDialogo == this.ID) { AnyadirMensaje(IDTema, mensaje); } else { Dialogo dialogo = BuscarDialogo(IDInteractuable, IDDialogo); dialogo.AnyadirMensaje(IDTema, mensaje); dialogo.AddToColaObjetos(); } } } //Comprobamos los objetos que cambian variables de grupos for(int i = 0; i < node.DevuelveNumeroGruposVariables(); i++) { int IDGrupo = node.gruposVariables[i].DevuelveIDGrupo(); int tipo = node.gruposVariables[i].DevuelveTipo(); int num = node.gruposVariables[i].DevuelveNumero(); int valor = node.gruposVariables[i].DevuelveValor(); //Si el grupo existe, cambiamos las variables if(Manager.instance.GrupoActivoExiste(IDGrupo)) { switch(tipo) { case 0: //suma la cantidad Manager.instance.AddVariablesGrupo(IDGrupo, num, valor); break; case 1: //establece la cantidad Manager.instance.SetVariablesGrupo(IDGrupo, num, valor); break; } } //Sino existe, comprobamos que no ha sido eliminado else { //Tras comprobar que no ha sido eliminado, lo añadimos a lista de grupos modificados if (!Manager.instance.GrupoAcabadoExiste(IDGrupo)) { Grupo grupo; //Comprobamos si el grupo modificado existe en la colaObjetos del Manager //Buscamos en la cola de objetos ColaObjeto colaObjeto = Manager.instance.GetColaObjetos(Manager.rutaGruposModificados + IDGrupo.ToString () + ".xml"); //Se ha encontrado en la cola de objetos if(colaObjeto != null) { ObjetoSerializable objetoSerializable = colaObjeto.GetObjeto(); grupo = objetoSerializable as Grupo; } //No se ha encontrado en la cola de objetos else { //Comprobamos si está en la lista de grupos modificados if (System.IO.File.Exists (Manager.rutaGruposModificados + IDGrupo.ToString () + ".xml")) { grupo = Grupo.CreateGrupo (Manager.rutaGruposModificados + IDGrupo.ToString () + ".xml"); } //Si no está ahí, miramos en el directorio predeterminado else { grupo = Grupo.CreateGrupo (Manager.rutaGrupos + IDGrupo.ToString () + ".xml"); } } switch (tipo) { case 0: //suma la cantidad grupo.variables [num] += valor; break; case 1: //establece la cantidad grupo.variables [num] = valor; break; } //Guardamos el grupo en la ruta de grupos modificados grupo.AddToColaObjetos(); } } } //Creamos un objeto inventario Inventario inventario; //Si se van a dar objetos, cargamos el inventario if(node.DevuelveNumeroObjetos() > 0) { //Buscamos el inventario en la colaobjetos ColaObjeto inventarioCola = Manager.instance.GetColaObjetos(Manager.rutaInventario + "Inventario.xml"); //Se ha encontrado en la cola de objetos if(inventarioCola != null) { ObjetoSerializable objs = inventarioCola.GetObjeto(); inventario = objs as Inventario; } //No se ha encontrado en la cola de objetos else { //Cargamos el inventario si existe, sino lo creamos if(System.IO.File.Exists(Manager.rutaInventario + "Inventario.xml")) { inventario = Inventario.LoadInventario(Manager.rutaInventario + "Inventario.xml"); } else { inventario = new Inventario(); } } //Comprobamos los objetos del nodo a añadir for(int i = 0; i < node.DevuelveNumeroObjetos(); i++) { int IDObjeto = node.objetos[i].DevuelveIDObjeto(); int cantidad = node.objetos[i].DevuelveCantidad(); //Añadimos el objeto inventario.AddObjeto(IDObjeto, cantidad); } inventario.AddToColaObjetos(); } //Comprobamos que nonmbres de los interactuablesvamos a cambiar for(int i = 0; i < node.DevuelveNumeroNombres(); i++) { int IDInteractuable = node.nombres[i].DevuelveIDInteractuable(); int indice = node.nombres[i].DevuelveIndiceNombre(); GameObject interactuableGO; //El nombre a cambiar es del interactuable del cual forma parte el dialogo if(IDInteractuable == -1) { interactuableGO = Manager.instance.GetInteractuable(this.IDInteractuable); } //El nombre a cambiar es de cualquier otro else { interactuableGO = Manager.instance.GetInteractuable(IDInteractuable); } //El interactuable se ha encontrado en la escena if(interactuableGO != null) { Interactuable interactuable = interactuableGO.GetComponent<Interactuable>() as Interactuable; //Si el objeto es un NPC, le cambiamos el nombre if(interactuable.GetType() == typeof(InteractuableNPC)) { InteractuableNPC interactuableNPC = interactuable as InteractuableNPC; int indiceActual = interactuableNPC.DevuelveIndiceNombre(); if (indiceActual < indice) { interactuableNPC.SetIndiceNombre(indice); interactuableNPC.AddDatosToColaObjetos(); //Actualizamos el interactuable para que muestre el nombre modificado interactuableNPC.SetNombre(interactuableNPC.DevuelveNombreActual()); } } } //El interactuable no se ha encontrado en la escena, lo buscamos en la cola de objetos o en directorios else { InterDatos interDatos; ColaObjeto colaObjeto = Manager.instance.GetColaObjetos(Manager.rutaInterDatosGuardados + IDInteractuable.ToString() + ".xml"); if(colaObjeto != null) { ObjetoSerializable objetoSerializable = colaObjeto.GetObjeto(); interDatos = objetoSerializable as InterDatos; } else { //Si existe un fichero guardado, cargamos ese fichero, sino cargamos el fichero por defecto if (System.IO.File.Exists(Manager.rutaInterDatosGuardados + IDInteractuable.ToString() + ".xml")) { interDatos = InterDatos.LoadInterDatos(Manager.rutaInterDatosGuardados + IDInteractuable.ToString() + ".xml"); } else { interDatos = InterDatos.LoadInterDatos(Manager.rutaInterDatos + IDInteractuable.ToString() + ".xml"); } } //Si el objeto es un NPC, le cambiamos el nombre if(interDatos.GetType() == typeof(NPCDatos)) { NPCDatos npcDatos = interDatos as NPCDatos; int indiceActual = npcDatos.DevuelveIndiceNombre(); if (indiceActual < indice) { npcDatos.SetIndiceNombre(indice); npcDatos.AddToColaObjetos(); } } } } //Comprobamos si hay alguna rutina que cambiar for(int i = 0; i < node.DevuelveNumeroRutinas(); i++) { int IDRutina = node.rutinas[i].DevuelveIDRutina(); ManagerRutina.instance.CargarRutina(IDRutina, false, false); } }
/// <summary> /// Adds the child to the children list. /// </summary> /// <param name="child">Child.</param> public void addChild(DialogueNode child) { children.Add(child); }
private void GotoNode() { if(NodeCurrentId < NodeList.Count) { NodeCurrent = NodeList[NodeCurrentId]; UpdateGUI(); } else EndConvo (); }
public void SetChild(DialogueNode child) { soleChild = child; }
public DialogueEdge() { from = new DialogueNode(); to = new DialogueNode(); }
public void AddNode(DialogueNode n) { nodeList.Add(n); }
public void SetFrom(DialogueNode f) { this.from = f; }
public LinkDialogueNodes(DialogueNode node) { parent = node; }
// Update is called once per frame void Update() { if (currentDialogue != null) { Option[] currentOptions = currentDialogue.currentNode.options; characterNameText.text = currentDialogue.currentNode.character.name; text = ""; text += currentDialogue.currentNode.characterText + "\n\n"; int optionNumber = 0; foreach (Option option in currentOptions) { text += (optionNumber + 1) + ". " + option.optionText + "\n"; optionNumber++; } if (newNode) { if (typeOutBools.Count > 0) { typeOutBools[typeOutBools.Count - 1] = false; } typeOutBools.Add(true); typingOut = true; StartCoroutine("TypeOut"); newNode = false; } if (Input.GetKeyDown(KeyCode.Space)) { if (typingOut) { skipTypeOut = true; typingOut = false; } } //If the player chooses an option, change the currentNode, // if the option was an exiting option, hide the dialogue window DialogueNode newCurrentNode = null; if (Input.GetKeyDown(KeyCode.Alpha1) && currentOptions.Length > 0 && currentOptions[0].IsChooseable()) { newCurrentNode = allDialogueNodes[currentOptions[0].linkedNode]; currentOptions[0].effects.ApplyEffects(); } else if (Input.GetKeyDown(KeyCode.Alpha2) && currentOptions.Length > 1 && currentOptions[1].IsChooseable()) { newCurrentNode = allDialogueNodes[currentOptions[1].linkedNode]; currentOptions[1].effects.ApplyEffects(); } else if (Input.GetKeyDown(KeyCode.Alpha3) && currentOptions.Length > 2 && currentOptions[2].IsChooseable()) { newCurrentNode = allDialogueNodes[currentOptions[2].linkedNode]; currentOptions[2].effects.ApplyEffects(); } else if (Input.GetKeyDown(KeyCode.Alpha4) && currentOptions.Length > 3 && currentOptions[3].IsChooseable()) { newCurrentNode = allDialogueNodes[currentOptions[3].linkedNode]; currentOptions[3].effects.ApplyEffects(); } else if (Input.GetKeyDown(KeyCode.Alpha5) && currentOptions.Length > 4 && currentOptions[4].IsChooseable()) { newCurrentNode = allDialogueNodes[currentOptions[4].linkedNode]; currentOptions[4].effects.ApplyEffects(); } if (newCurrentNode != null) { SetCurrentNode(newCurrentNode, newCurrentNode.exitDialogue); } } }