0
\$\begingroup\$

I'm developing a simple NPC controller that the player can talk with.

At the moment a NPCController script on the NPC gameobject manages several "high level" feature of the NPC such as intelligence.

Every time the player talks with the NPC, the latter will respond with "Bzz", "Hello" or "Heya" depending on his intelligence level.

The talking part is implemented in a TalkController script. I did this way in order to have multiple behaviours depending on the player/npc interaction without creating a giant NPCController class. Plus some NPC may not speak at all (in this case I'd simply remove the TalkController).

I have a small dilemma on how to change the NPC response in TalkController based on the intelligence level in NPCController.

I could use Events:

// NPCController.cs

public delegate void OnIntelligenceLevelHandler(int level);
public static event OnIntelligenceLevelHandler OnIntelligenceLevelChanged;

// When intelligence increases
OnIntelligenceLevelChanged(2);

and:

// TalkController.cs

// Store _intelligence = 1;
// Subscribe to OnIntelligenceLevelChanged
// Upgrade _intelligence when the event fires
// Switch word on _intelligence when talking

I could use a direct reference:

// TalkController.cs

// Store _npccontroller = GetComponent<NPCController>();
// Switch word on _npccontroller.Intelligence when talking

What would be the best approach?

\$\endgroup\$
0
\$\begingroup\$

In your specific use-case, I'd say both are good.

The reference method will give you access ofc to all the other public elements of NPCController, so that's a plus if needed, whereas the event method will keep the objects decoupled.

The events in C# are there to implement very easily the observer pattern, keeping the observed and the observed decoupled and making "things happen" in more than one place when the observed object raises the event.

Getting references is useful when you need to access directly more than one element of the referenced object, but that goes with a strong coupling between the referenced and the referencer objects.

Personally, I like to use events if I don't need to access more than one element in the observed object, just to keep things "safer" in some way (I like to keep objects decoupled the most I can).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.