Reader small image

You're reading from  Learning C# by Developing Games with Unity - Seventh Edition

Product typeBook
Published inNov 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781837636877
Edition7th Edition
Languages
Tools
Right arrow
Author (1)
Harrison Ferrone
Harrison Ferrone
author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone

Right arrow

Basic AI and Enemy Behavior

Virtual scenarios need conflicts, consequences, and potential rewards to feel real. Without these three things, there’s no incentive for the player to care about what happens to their in-game character, much less continue to play the game. And while there are plenty of game mechanics that deliver on one or more of these conditions, nothing beats an enemy that will seek you out and try to end your session.

Programming an intelligent enemy is no easy task, and often goes hand in hand with long working hours and frustration. However, Unity has built-in features, components, and classes we can use to design and implement AI systems in a more user-friendly way. These tools will push the first playable iteration of Hero Born over the finish line and provide a springboard for more advanced C# topics.

In this chapter, we’ll focus on the following topics:

  • The Unity navigation system
  • Static objects and navigation meshes
  • ...

Moving enemy agents

Our patrol locations are set and the Enemy Prefab has a NavMeshAgent component, but now we need to figure out how to reference those locations and get the enemy moving on its own. To do that, we’ll first need to talk about an important concept in the world of software development: procedural programming.

Procedural programming

Even though it’s in the name, the idea behind procedural programming can be elusive until you get your head around it; once you do, you’ll never see a code challenge the same way.

Any task that executes the same logic on one or more sequential objects is the perfect candidate for procedural programming. You already did a little procedural programming when you debugged arrays, lists, and dictionaries with for and foreach loops. Each time those looping statements were executed, you performed the same call to Debug.Log(), iterating over each item sequentially. The idea now is to use that skill to get a more useful...

Enemy game mechanics

Now that our enemy is on a continuous patrol circuit, it’s time to give it some interaction mechanics of its own; there wouldn’t be much risk or reward if we left it walking around with no way to act against us.

Seek and destroy: changing the agent’s destination

In this section, we’ll be focusing on switching the target of the enemies’ NavMeshAgent component when the player gets too close and dealing damage if a collision occurs. When the enemy successfully lowers the player’s health, it will return to its patrol route until its next run-in with the player.

However, we’re not going to leave our player helpless; we’ll also add in code to track enemy health, detect when an enemy is successfully hit with one of the player’s bullets, and when an enemy needs to be destroyed.

Now that the Enemy Prefab is moving around on patrol, we need to get a reference to the player’s position and...

Refactoring and keeping it DRY

The Don’t Repeat Yourself (DRY) acronym is the software developer’s conscience: it tells you when you’re in danger of making a bad or questionable decision, and gives you a feeling of satisfaction after a job well done.

In practice, repeated code is part of programming life. Trying to avoid it by constantly thinking ahead will put up so many roadblocks in your project that it won’t seem worthwhile carrying on. A more efficient—and sane—approach to dealing with repeating code is to quickly identify it when and where it occurs and then look for the best way to remove it. This task is called refactoring, and our GameBehavior class could use a little of its magic right now.

You may have noticed that we set the progress text and timescale in two separate places, but we could easily make ourselves a utility method to do this for us in a single place.

As you get more comfortable with programming...

Summary

With that, our enemy and player interactions are complete. We can dish out damage as well as take it, lose lives, and fight back, all while updating the on-screen GUI. Our enemies use Unity’s navigation system to walk around the arena and change to attack mode when within a specified range of the player. Each GameObject is responsible for its behavior, internal logic, and object collisions, while the game manager keeps track of the variables that govern the game’s state. Lastly, we learned about simple procedural programming and how much cleaner code can be when repeated instructions are abstracted out into their methods.

You should feel a sense of accomplishment at this point, especially if you started this book as a total beginner. Getting up to speed with a new programming language while building a working game is no easy trick. In the next chapter, you’ll be introduced to some intermediate topics in C#, including new type modifiers, method overloading...

Pop quiz—AI and navigation

  1. How is a NavMesh component created in a Unity scene?
  2. What component identifies a GameObject to a NavMesh?
  3. Executing the same logic on one or more sequential objects is an example of which programming technique?
  4. What does the acronym DRY stand for?

Don’t forget to check your answers against mine in the Pop Quiz Answers appendix to see how you did!

Join us on discord!

Read this book alongside other users, Unity game development experts and the author himself.

Ask questions, provide solutions to other readers, chat with the author via. Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/csharpwithunity

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity - Seventh Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781837636877
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone