Kodeco Forums

How to Create a Tower Defense Game in Unity – Part 2

In this second and final part of the Unity tower defense tutorial, you'll add some shooting monsters into the the mix.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/268-how-to-create-a-tower-defense-game-in-unity-part-2

@jayfeesh

float distanceToGoal = enemy.GetComponent().DistanceToGoal();

I keep getting this error for this line:

Assets/Scripts/ShootEnemies.cs(29,59): error CS1061: Type MoveEnemy' does not contain a definition for DistanceToGoal’ and no extension method DistanceToGoal' of type MoveEnemy’ could be found. Are you missing an assembly reference?

any idea on how to fix this?

Loving the tutorial btw :slight_smile:

@dobbie1324 Glad you’re enjoying the tutorial!

You have: float distanceToGoal = enemy.GetComponent().DistanceToGoal();
You need: float distanceToGoal = enemy.GetComponent<MoveEnemy>().DistanceToGoal();

Also, make sure you have the following method in your MoveEnemy script:

public float DistanceToGoal()
{
  float distance = 0;
  distance += Vector2.Distance(
      gameObject.transform.position, 
      waypoints [currentWaypoint + 1].transform.position);
  for (int i = currentWaypoint + 1; i < waypoints.Length - 1; i++)
  {
    Vector3 startPosition = waypoints [i].transform.position;
    Vector3 endPosition = waypoints [i + 1].transform.position;
    distance += Vector2.Distance(startPosition, endPosition);
  }
  return distance;
}

Hello everyone.

I really liked the tutorial, but I had some doubts.

1 - In the enemy movement issue, in some TD games like Kingdom Rush, enemies seem to follow 3 or more path lines. In that case would it be waypoint sequences? or are you using another method like pathfinde?

2 - How would the order control of the sprites be when the towers were in front of the enemies going through a path behind the tower and then in a path in front? Would you create points indicating when to change the order of the enemy?

Thank you for your help.

@jayfeesh Can you please help with this when you get a chance? Thank you - much appreciated! :]

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!