Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Attaching Canvas Made Dialogue to Object

Discussion in 'Scripting' started by Mick_Ash, Nov 18, 2023.

  1. Mick_Ash

    Mick_Ash

    Joined:
    Oct 6, 2023
    Posts:
    28
    Hello, all!

    I made a dialogue system following a tutorial by BMO, but I want to attach it to an object that will call the dialogue when interacted with (hence, pressing the enter button while colliding with the object causes the dialogue to start). How would I go about attaching the canvas or the dialogue panel to the object I want to interact with?

    Code is here:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class JamesDialogueScript : MonoBehaviour
    7. {
    8.     public TextMeshProUGUI textComponent;
    9.     public string[] lines;
    10.     public float textSpeed;
    11.  
    12.     private int index;
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.         textComponent.text = string.Empty;
    17.         startDialogue();
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if(Input.GetKeyDown(KeyCode.Return))
    24.         {
    25.             if (textComponent.text == lines[index])
    26.             {
    27.                 nextLine();
    28.             }
    29.             else
    30.             {
    31.                 StopAllCoroutines();
    32.                 textComponent.text = lines[index];
    33.             }
    34.         }
    35.     }
    36.  
    37.     void startDialogue()
    38.     {
    39.         index = 0;
    40.         StartCoroutine(typeLine());
    41.     }
    42.  
    43.     IEnumerator typeLine()
    44.     {
    45.         foreach (char c in lines[index].ToCharArray())
    46.         {
    47.             textComponent.text += c;
    48.             yield return new WaitForSeconds(textSpeed);
    49.         }
    50.     }
    51.  
    52.     void nextLine()
    53.     {
    54.         if (index < lines.Length - 1)
    55.         {
    56.  
    57.             index++;
    58.             textComponent.text += string.Empty;
    59.             StartCoroutine(typeLine());
    60.         }
    61.         else
    62.         {
    63.             GameObject.SetActive(false);
    64.         }
    65.     }
    66. }
     
  2. Mick_Ash

    Mick_Ash

    Joined:
    Oct 6, 2023
    Posts:
    28
    Code issue: I edited the
    Code (CSharp):
    1. GameObject.SetActive(false)
    to
    Code (CSharp):
    1. gameObject.SetActive(false)