What Do You Need to Know | How do we get started?
There is a lot to consider when programming an NPC to talk. For instance: how far away do you have to stand? Do you have to be facing them when you talk to them? Do they have to be facing you? How do you want them to respond? How many different options for dialogue do you want them to have? Are there special circumstances that trigger special dialogue options? Are they an important NPC that is related to your current quest?
Setting Up Files | The Relatively Easy Stuff
When programming in Unity, you have to give yourself something basic to work with. So, start by creating a folder in the Project pane. You are going to be putting prefabs inside this folder, so name it accordingly. Inside this folder, create a new Prefab, and call it something related to NPC Dialog. Make a new folder, move it into the Prefabs folder, and call it "Scripts". Make a C# script, name it exactly the same as the prefab, and that will be your playground for the fun stuff.
Implementation | The Dirty Work
Load your NPC object into Unity. Create an empty GameObject in the game window, and name it something related to NPC Dialog. In the Inspector window, go to "Add Component", scroll to "Physics", and add a "Box Collider". The Box Collider will allow you to set an event to the area inside the box. Make sure that "Is Trigger" in the Box Collider menu pane is checked.
Drag the C# script onto the name of GameObject (not the NPC object). Then, drag the GameObject onto the NPC Dialog prefab. You can delete the GameObject from the Hierarchy window. Drag the prefab onto the name of your NPC object in the Hierarchy window. NOTE: If the GameObject disappears from the game window, don't panic! Click on the GameObject in the Hierarchy window, then click the settings icon next to Transform in the Inspector window, and click "Reset Position". It will warp the GameObject back to your NPC.
The Script | Finally! The code!
Go ahead and open up the C# script. It will open up to a mostly blank .cs file, with only the headers and the establishment of a class with the same name as the C# script. Start out by establishing two public string arrays--one for storing the NPC's dialog options, and the other for storing the player's possible responses. Create a bool for displaying the dialog and set it to false. Create a void function called "onGUI", but leave it empty for now. onGUI will be responsible for displaying the dialog when we get there.
Save your script and pop back into Unity. In the Inspector window, you should see both of your string arrays towards the bottom. You can edit and fill these through Unity! Decide how many dialog options you want, and go ahead and put that number in the size spot. That respective number of elements should show up and be available to edit. You can fill those in with your chosen strings of dialog, no quotations necessary.