Your game is coming along. You have aliens moving at the space marine and the aliens will not take ‘no’ for an answer. Unfortunately, there are some issues.

First, your aliens are updating their destination every frame. This is a little resource intensive. You might be able to change it.

Next, when the aliens collide with the marine, they should die. Currently, they are pushing your marine high into the air.

Finally, the GameManager needs some additional tuning. You’ll do this all in the following tutorial.

Note: This tutorial is part of a collection that teaches Unity development from the ground up. You can read the entire series over here. This series is free and does not require any account creation. All assets are provided. If you find it useful, feel free to buy me a coffee.

Tuning the pathfinding

Although the pathfinding appears to work without any issue, you actually have a significant problem to solve. Every time you assign a destination to a NavMeshAgent, Unity goes through the process of a calculating a route to that destination.

It wouldn’t be a big deal if it happened here and there, but consider that the game will spawn many aliens and perform this calculation each time. Review your implementation with that fact in mind. You’ll see that you’re calculating the pathfinding once per frame.

This isn’t scalable — there will be more pathfinding calculations when aliens spawn. Eventually, your frame rate will tank and it’ll kick off a tragic chain of events for your player.

Open Alien.cs in your code editor. Under the public variables, add the following:

[SerializeField]
private float navigationUpdate;

private float navigationTime = 0;

navigationUpdate is the amount of time, in milliseconds, for when the alien should update its path. navigationTime is a private variable that tracks how much time has passed since the previous update.

In Update(), replace agent.destination = target.position with the following:

navigationTime += Time.deltaTime;
if (navigationTime > navigationUpdate) 
{
  agent.destination = target.position;
  navigationTime = 0;
}

This code checks to see if a certain amount of time has passed then updates the path.

Switch back to Unity. In the Project view, select the Alien prefab in the Prefabs folder. In the Alien script, set the Navigation Update field to 0.5.

Now play your game. You’ll notice the aliens are a little slower to dial in on the marine but, for the most part, they will get to him.

At this point, you’d want to play around with the variables that affect play and performance to find that balance point. Testing and profiling your game is the only way to find the right config!

Updating Alien collisions

You now have hordes of aliens chasing a marine. There’s just one thing left to be done — you need something to happen when the marine blows them to bits.

Switch back to Alien.cs in your code editor and add the following code before the last closing brace:

void OnTriggerEnter(Collider other) 
{
  Destroy(gameObject);
}

This code works like a typical collision code, except that it makes the collision event into a trigger. Why a trigger? Remember, you set the alien’s Rigidbody to Is Kinematic, so the Rigidbody won’t respond to collision events because the navigation system is in control.

That said, you can still be informed when a Rigidbody crosses a collider through trigger events. That way, you can still respond to them. In this case, you call Destroy() and pass in the gameObject, which will delete the alien instance. Save the file and switch back to Unity.

Select the Alien in the Prefabs folder, and in the Inspector, look for the Sphere Collider. Check the Is Trigger checkbox.

This shows the Sphere Collider with the Is Trigger set to true

At this point, anything that collides with the alien will kill it — walls, columns, the marine, etc. You need to opt out of some collisions.

With the Alien prefab still selected, assign it to the Alien layer. When prompted to apply the layer to all child objects as well, select No, this object only.

Note: In the original book, you actually use the Alien head for some physics calculations. Since the model is different, it may not be necessary to have the layer apply to just the parent GameObject. I’m keeping as-in to avoid causing errors in a subsequent chapter.

Next, in the Project window, select the BobbleArena-Column in the Prefabs folder. In the Layer drop-down, assign it to the Column layer and select Yes, change children in the subsequent prompt dialog.

Next, click Edit Project Settings Physics. In the collision matrix, uncheck the following in the Alien row: Column, Upgrade, Alien Head, Floor.

This shows the collision matrix.

Play your game.

Now you can shoot aliens to your heart’s content, and, when you collide with them, they’ll despawn. In a later chapter, you’ll give the aliens a more fitting death. But as it is now, you can get a good feel for your game.

Making live changes

Your game is a little flat. Restart your game, and pause right as it starts.

This is the pause button on the Unity play controls.

Select the GameManager in the Hierarchy, and in the Inspector, set the following values:

  • Max Aliens On Screen: 50
  • Total Aliens: 50
  • Min Spawn Time: 0
  • Max Spawn Time: 3
  • Aliens Per Spawn: 3

Now unpause the game, and prepare to be confronted by a lot of aliens. If you experience a slowdown, dial back the numbers until you find what works best for your system.

Once you find the right amount, pause the game one more time. Do not stop the game. You need to copy the GameManager values. You could write them down, but there’s a better way.

Select GameManager in the Hierarchy (if it isn’t already) and, in the Inspector, click the settings icon over the Game Manager script component. From the drop-down, select Copy Component.

This shows copying the component.

Now stop your game. Pay no attention to the fact that the GameManager reverts the values. Click the settings icon again and select Paste Component Values.

This shows pasting the component values.

The component will update with all the values you added during run time. Pretty awesome, eh? The downside is that you can only do this with one component at a time.

Where to go from here

It’s hard to believe that one little chapter on pathfinding could bring a relatively static game to life. You can download the completed project over here:

https://drive.google.com/file/d/1aMkCXHTR7faDR1ba8hhORPFeEggRS3-P/view?usp=drive_link

As you worked through the process of pathfinding, you learned about:

  • Creating Managers, such as a GameManager to manage the gameplay and allow you to tweak settings in real time.
  • NavMeshes and how they define movable areas for GameObjects.
  • NavAgents and how to build them and give them targets.
  • NavObstacles to have your agents avoid various parts of your level geometry.

Not surprisingly, there’s much more to learn. Have you noticed that everybody moves without moving their legs? Curious. In the next chapter, Chapter 6, “Animation,” you’ll give your models a little spring in their step and learn all about Unity’s animation system in the process. You’ll do this in the next tutorial.


Discover more from Jezner Blog

Subscribe to get the latest posts sent to your email.

By Brian Moakley

Brian Moakley is a writer and editor who lives amongst the quiet hills in New England. When not reading tales of high adventure, he is often telling such stories to all who will listen.

Related Post

Leave a Reply