UNITY 2D NPC DIALOGUE SYSTEM TUTORIAL
HTML-код
- Опубликовано: 27 сен 2024
- In this tutorial we will look at how to make an NPC system with a dialogue box similar to games like Stardew Valley!
********************************
Discord discord.io/div...
Patreon / diving_squid
Play my games! diving-squid.i...
********************************
If you have any problems, let me know in the comments!
Bye :)
For the people struggeling with getting the code to work correctly; I found that the statement (dialogueText.text == dialogue[index]) always returned false until you tried talking to the npc for the second time. This was because the length of dialogueText string started as 1. To fix this you just have to add:
void Start()
{
dialogueText.text = "";
}
And for people wanting to change the continue button out with an interact button like E, you can use this code instead:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class NPC : MonoBehaviour
{
public GameObject dialoguePanel;
public TextMeshProUGUI dialogueText;
public string[] dialogue;
private int index = 0;
public float wordSpeed;
public bool playerIsClose;
void Start()
{
dialogueText.text = "";
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if (!dialoguePanel.activeInHierarchy)
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
else if (dialogueText.text == dialogue[index])
{
NextLine();
}
}
if (Input.GetKeyDown(KeyCode.Q) && dialoguePanel.activeInHierarchy)
{
RemoveText();
}
}
public void RemoveText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach(char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if (index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
RemoveText();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerIsClose = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerIsClose = false;
RemoveText();
}
}
}
Just wanted to thank you for your help here, i was trying to get this to work for my university project and you really saved my butt, Thanks!
I'm having a problem where the NPC can detect when the player is close, but pressing the interact key does nothing, when tinkering with the code and removing the interact key, all works fine, but when adding it back in the code doesn't work.
@@Cammywell By accident I wrote:
"if (Input.GetKeyDown(KeyCode.Q) && playerIsClose)",
but I meant to write:
"if (Input.GetKeyDown(KeyCode.E) && playerIsClose)"
Maybe that is what ruining your code? Because I made it such that you can cancel the dialogue by pressing Q in the if statement under.
@@ryanoneill9862 No problem! Good luck with your project 😊
@@lovfall642 I tried changing the input to various different inputs but eventually found that just taking out the if statement which detects if the dialogue panel is active in the hierarchy fixed the whole thing. Although when I press the interact button it restarts the dialogue even while the dialogue is currently playing. I can’t really figure out a fix for that, is there a function in unity which will disable a certain input while the window is open?
ur tutorials are really cool and helpful, i appreciate ur existence
thank you so much for this tutorial!! i was stuck on this for over 10 hours, i just couldn't do it and i've tried multiple tutorials but they didn't work or requiered 3 or more scripts which is confusing to me as a beginner in C#. this tutorial worked and i'm SO glad!!!! thanks!!!
thank you so much for this tutorial! i was struggling with my dialogue system for a long while until i found this and it works perfectly!!
glad to see your still making videos!
your multiplayer serries was very helpful.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NPC : MonoBehaviour
{
public GameObject dialoguePanel;
public Text dialogueText;
public string[] dialogue;
private int index = 0;
public float wordSpeed;
public bool playerIsClose;
void Start()
{
dialogueText.text = "";
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if (!dialoguePanel.activeInHierarchy)
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
else if (dialogueText.text == dialogue[index])
{
NextLine();
}
}
if (Input.GetKeyDown(KeyCode.Q) && dialoguePanel.activeInHierarchy)
{
RemoveText();
}
}
public void RemoveText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach(char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if (index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
RemoveText();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
playerIsClose = true;
}
private void OnTriggerExit2D(Collider2D other)
{
playerIsClose = false;
RemoveText();
}
}
You’re the type of guy to say “you get what you get and you don’t throw a fit”
It's a good tutorial and it works fine on 1 NPC, but I have problem with the other NPC's continue button as it doesn't continue
Not sure if solved for you, consider adding UI directly to the NPC with their own canvas.
Have separate UI for the player canvas with the continue button
When the npc loads up their canvas, wire the continue button to them through code.
Dragging and dropping things via the engine doesnt work that great for scalability and quickly becomes over combersome.
This approach i mentioned would allow things such as chat bubbles above an npc head at any given moment without disruptting another npc.
A thought on how to write the continue button from the player to npc is to just use the collision system as shown in the video, grab the reference for the continue button at that time.
Just a quick thought.
this is insanely helpful thank you so much! loads more helpful than so many other tutorials i tried lol
What a great Tutorial, your channel deserves more subscribers 👍
exactly what i needed! thank you for a simple and easy to follow tutorial!
ngl, the code just doesn't work at all for me.
Incredibly good tutorial! Thank you :D
Yo thank you so so much dude! made it so easy to follow as well!
Thank you very much I'm from Thailand I got a lot of knowledge from you. i made it is a big project Without your script it would be bad. Thank you for giving good things to each other.😍😍🙏🙏
Very helpfull video, thank you
For some reason, nothing happens to me for dialogue. I checked my code and there are 0 errors.
UPDATE: I AM GETTING a Null Reference Exception error HELP!
You desirve way way way more subscribers! Your tutorials are soooo goooood
Awesome video for people like me who don't know how to program!!
I have a question that if I want to press E to start the dialogue and keep pressing E for the next sentence, how can I do with the code?
it only works for 1 NPC if i do it on the second it takes the text from the first one
Yes, I have same problem .
did u figure out a fix?
@@parasyte8230 nope
I made a continueButton for every NPC and dragged each NPC into that button.
thank you so much, its really helpful for beginner like mee :)
i did all you did but the dialogue panel is not really showing when I'm near my npc
Thank you soooo much!! I needed this
I think there is a bug for when you have long sentences and keep pressing on whatever button you have for interacting with the npc, letters from the other sentences start appearing. Any ideas on why this is happening?
I am having the same problem
Before every "StartCoroutine(Typing());" add a line saying:
StopAllCoroutines();
A coroutine runs on its own, so it'll keep typing even if you move on to a new line - or close the dialogue box and reopen it! So you must call stop to make it stop typing any previous sentences.
(I plan on making a video on my channel with an updated npc dialogue system! :-))
@@GameCodeLibrary But the text from the previous coroutine continues to appear, do you have any idea why ?
nvm i found why : i added dialogueText.text = ""; in the update method, everything works perfectly
@@Ashe912 where exactly did you put the "dialogueText.text = "; " in the update method? I am having the same problem as you.
It wont let me put anything into the Dialogue Text box when we’re supposed to drag in the DialogueText at the end
by pressing E thrice, the previous message will overlap with the new messages..
Why is it that whenever and wherever i am when i press even if im miles away the text shows up please help
When ever i try to run the code it says that "GameObject does not have a definition for text"
Soo helpful but i got stuck cos I didn’t know u needed a rigidbody2D on your player
Is there a way to make this work with TextMeshPro?
Thank you so much for this!
how would i make something when the player walks up to the npc theyre able to indicate to press e to talk
hi there white noise in the mic I don't know if it is intentional or not but you can reduce the noise in audacity... anyways awsome tut thanks a lot!😃
How would you do this with multiple NPCs in one scene?
hi why is my dialogue panel not showing when I play the game
Hey diving_squid, keep up! Good content! I hope you're doing well and you'll be back with new videos soon!
Hello there, great video! I was wondering how the code would look like with the new input system
thank you very much
seems like a good tutorial but it doesnt work for me :/ when i run the game and press the E button and all that, the dialogue box doesnt show up at all. i can see in the hierarchy that it gets activated and deactivated but i cant see it
did you ever find a solution? or a different tutorial please im dying over here
sanem dosn't work
@@lolerishype Check my other comment
Did anyone get it to work with multiple NPCs instead of one? I tried making it for more than one, but it keeps using the previous dialogues when I added a new dialogues to a new npc in a different scene?
did you ever find a fix to this?
if it wasnt for yt tutorials like this, my game would look like crap lmao
Your channels amazing! Could you do Godot tutorials?
it says Assets\Npc.cs(45,13): error CS0106: The modifier 'public' is not valid for this item
Thank you :3
Great tutorial, but do you think you can make one where you can have a different image for each npc, thanks
For some reason the text just doesn't show up on the panel, the continue button does but the text doesn't
Yeah i have that problem too but with everything
I fixed my problem, now i have the same problem of you
Make sure that the text is above the panel layer
Does anyone know why the dialogue box only appears if I am not on the 'Maximize on play' feature? If I keep my game window like in the video it works but if it's maximized it doesn't show anything at all. Any suggestions? please
For some reason it wont let me drag the dialogue text into the dialogue text box to insert in into the NPC script?
I have the same problem, did you find a way to fix it?
@@Aftiz_MD It's really stupid, but the dialogue text has to have the Text component, not TextMeshPro. It's hidden under Legacy in the UI menu. That fixed the issue for me.
OR! (i just found this lol) Change "public Text nametext" to "public TextMeshProUGUI nametext", and add "using TMPro" at the top.
for me it said that the dialogue text was a game object with the weird text mesh pro thing, and I can't get regular text, so now I'm stuck because it will only accept a text to go with the dialogue text variable.
Heyy Lachlan, if you change the dialogue Text variable in the code to TMP text it will work for you. like this:
public TMP_Text dialogueText; instead of public Text dialogueText;
you will also need to ensure you have text mesh pro in your collections by adding:
using TMPro;
to the top of your script
Thanks bro,
GOSTARIA DE VER COMO NO DIALOGO O PLAYER TAMBEM FALAR. TODOS OS TUTORIAIS QUE VEJO, APENAS O NPC DIZ FRASES E O PLAYER FICA MUDO EM CENA. E ISTO NÃO SERIA UM DIALOGO, E SIM UM MONOLOGO. KKK
is there a way to create a prompt to talk to the npc?
This tutorial was very helpful, thx!
Also you have a really cute voice :)
Ребят подскажите как исправить этот код чтобы он работал на платформе андройд как вместо клавиши сделать кнопку
perfect
the "playerisclose = true" statement doesnt work for me? it says its not a valid name in that context. How do i fix this? I use C#
check how you write it. if your variable name is "playerIsClose" but you are writing it as "playerisclose = true" then it will not recognize your variable.
where more tutorials? *Confused apenoises
pls mobil how to make ???
Hey! Thanks for the tutorial, very useful. I have a question, though: Instead of pressing E to both enable and disable the menu, I added a Goodbye button. It works, but now I want to disable the continue button when my NPC is saying the last line of dialogue. How would I do this? (Because the continue button and goodbye button do the same thing in that situation.)
Check if the index is equal to the last string of the dialogue, and change the text element to Goodbye. And default the text element to Continue.
@@lovfall642 ty will try
finaly new video please pin
note to self: this dialogue system sucks and absolutely does not scale up well, at least not with the standing skills that i have with unity atm. i had to make different buttons individually for every npc, and then manually assign them, which fucking sucked. there are absolutely better dialogue systems out there, they may be a bit more complex to set up initially but they will save you so much time down the line.
can i get a link?
im having the same trouble with multiple NPCs
@@blasen_schlampe1108 unfortunately since i was developing for a 24 hour game jam i didn't manage to find any links :( however i'm sure there are better systems out there on youtube
@@shadowfire04 found a work around justt copy and paste them and name them to each NPC/item interaction kinda like you said
idk if u can check but i attempted to do the code but many errors pp up. have i done anything wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NPC : MonoBehaviour
{
public GameObject dialoguePanel;
public Text dialogueText;
public string[] dialogue;
private int index;
public float wordSpeed;
public bool playerIsClose;
void Update()
{
if(Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if(dialoguePanel.activeInHierarchy)
{
zeroText();
}
else
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
}
}
public void zeroText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach(char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if(index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
zeroText();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.CompareTag("Player"))
{
playerIsClose = false;
zeroText();
}
}
}
what are the errors?
Holy cow! This is beautiful and can scale to multiple NPC's very easily. Outstanding work!
It wont let me put anything into the Dialogue Text box when we’re supposed to drag in the DialogueText at the end
It wont let me put anything into the Dialogue Text box when we’re supposed to drag in the DialogueText at the end
Hi! Thanks for the tutorial, but how can i do dialogue with more than one npc??
hi, for some reason whenever i press E even if im not at the chest the texts pop up, how can i fix that?
What do you suggest me for 3d version of this ?
It wont let me put anything into the Dialogue Text box when we’re supposed to drag in the DialogueText at the end
woww, this is such a great tutorial, thank you very much!! i have just one doubt, how could i be able to print some parts of the text in color? it seems that wouldnt work very well here
the code is to hard to follow , and i get a error : the modifier public is not valid
for this item , i get this at ny funtion , private and public
Kinda cool, but why aren’t you active on discord ._.
Thanks for the help, finally have a dialogue system working because of this video, is there a way to disable the E button once a dialogue is active so the player can cycle through all the texts using the continue button and not accidentally closing the dialogue panel by pressing E a second time
I don’t know what to say! I’m begging you keep making these wonderful videos please!!
Thanks
I have a question. How do I make it work for a 3d video game, because I did it the same way, but the whole Dialogue Panel doesn't show up? I'll appreciate any help :)
it didnt work for me in 100%, when i press e the dialoguePanel is showing up but the game stops, so overall nice tutorial but i will need to fix a few things xc
for whose only can see a single letter display. check your wordSpeed and edit it to 0.06.
It wont let me put anything into the Dialogue Text box when we’re supposed to drag in the DialogueText at the end
taşşağına kurban
I have error:
Assets\NPC.cs(7,18): error CS8652: The feature 'constant interpolated strings' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.
Idk how
same
how do you make it so that you can continue the text without the button but instead just pressing E again?
Thank you so much for this tutorial!
What a lovely tutorial
You are to fast in explaining¨
Tag: player is not defined
even though i have added the player tag on my player whats goin on?
capitalise the "Player"
my button and tezt doesnt show up
absolutely amazing
u are live saver thank youu
you just saved my butt
Hey! Where’d you go?
thank you, sick tutorial
thanks
tkss
Thank you so much!
bus
I am learning well.
I am making a tutorial through a dialog.
So I have a few questions, so I'll leave a comment.
I want the NPC to stop the conversation in the middle, take an action, and then resume the previous conversation when certain conditions are met.
Where can I fix this?
Maybe try adding something to your code. In my opinion it should look like this:
next part of the dialogue>
hi, maam @diving_squid nice tutorial but I follow the same code but it's looping on me how to fix it thank you.
Thanks You + I edit the script to make it work in 3D Project : using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class NPC : MonoBehaviour
{
public GameObject dialoguePanel;
public TextMeshProUGUI dialogueText;
public string[] dialogue;
private int index = 0;
public float wordSpeed;
public bool playerIsClose;
void Start()
{
dialogueText.text = "";
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E) && playerIsClose)
{
if (!dialoguePanel.activeInHierarchy)
{
dialoguePanel.SetActive(true);
StartCoroutine(Typing());
}
else if (dialogueText.text == dialogue[index])
{
NextLine();
}
}
if (Input.GetKeyDown(KeyCode.Q) && dialoguePanel.activeInHierarchy)
{
RemoveText();
}
}
public void RemoveText()
{
dialogueText.text = "";
index = 0;
dialoguePanel.SetActive(false);
}
IEnumerator Typing()
{
foreach (char letter in dialogue[index].ToCharArray())
{
dialogueText.text += letter;
yield return new WaitForSeconds(wordSpeed);
}
}
public void NextLine()
{
if (index < dialogue.Length - 1)
{
index++;
dialogueText.text = "";
StartCoroutine(Typing());
}
else
{
RemoveText();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
playerIsClose = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
playerIsClose = false;
RemoveText();
}
}
}