简体   繁体   中英

Unity 3D: Game Object interaction

Assuming we have one first person character and several NPC AIs. The first person character should be able to talk to the NPC AI's (via dialog service). My problem is: How should I "connect" the two game objects (FPC and NPC) to each other?

So he can basically walk around and talk to them, then they answer something, and the first person character may choose an option.

I see several options here:

  1. add a public variable to 'first person character'. this public variable will hold the NPC AI. So the NPC AI and first person character can talk to each other via functions on both classes.
  2. Add a class 'DialogService' which implements the observer pattern. So there will be several publishers and subscribers. My problem here is how to hook up the NPCs and first person character to each other
  3. Maybe you have a better alternative?

If you're looking for a simple solution, I could offer this:

Inside of the character's GameObject have another GameObject called, let's say, "Dialog Collider". Add a collider component to that game object, make it (the collider) a trigger. Also, I would advise you to make the collider a cylinder with a larger radius so that you can enter dialog without actually colliding with another character.

Add a script your player character that starts the dialog when the "Dialog Collider" enters the collision with another GameObject of same name/tag. At this point I presume you would have the same setup for all game character: they all should have a "Dialog Collider" GameObject inside of the main GameObject, if they have a dialog option to begin with that is.

That way you can leave the collision detection to the UnityEngine and not check for it every frame.

Also, I'd advise to make a generic Dialog script; make it an abstract class that you can inherit from to override some methods so you'd have all the basic functionality right from the start and enough flexibility to change/extend the behaviour of the NPC later on.

Or make a IDialogCharacter interface and implement the methods and dialogs manually for every class; use polymorphism to your advantage to check for the IDialogCharacter interface if you prefer composition over inheritance.

As the hooking up part - when the collision begins your player character will be able to fetch the script (first get the colliding GameObject, then the script component) of the other character and request the dialog start from the other character or get some data object from the other character and start the dialog.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM