Would this code solve the problem too?

Hi guys!
Happy new year! I have solved the challenge in this lecture this way and wanted to ask if it is also viable? (I got rid of all my red lines. So it should…)

public class EnemyPathing : MonoBehaviour
{
    WaveConfig waveConfig;
    List<Transform> waypoints;
    float moveSpeed;
    int waypointIndex = 0;

    // Start is called before the first frame update
    void Start()
    {
        waypoints = waveConfig.GetWaypoints();
        moveSpeed = waveConfig.GetMoveSpeed();
        transform.position = waypoints[waypointIndex].transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    private void Move()
    {
        if (waypointIndex <= waypoints.Count - 1)
        {
            var targetPosition = waypoints[waypointIndex].transform.position;
            var movementThisFrame = moveSpeed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

            if (transform.position == targetPosition)
            {
                waypointIndex++;
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

I’m not quite sure in what context you’re trying to ask, but generally speaking, my answer would go along the line of, “Does it work?” Are there any problems? If it works and there are no problems, then it’s viable.

It has been solved in another way in the video. Hence my question…

Then to be able to answer, you’d have to explain to me the challenge you were trying to solve and what the differences between the approaches.

This was the solution in the video. ‘moveSpeed’ has been replaced by the method in the Config directly. Whereas I have created a variable.

Hi,

Good job on developing your own approach. To figure out whether your code solves the problem, you must test it. If it fixes the problem, it’s a solution by definition. :slight_smile:

2 Likes

I get what you did now.

Yeah, it’s mostly fine. It’s a good idea to look for areas where you can improve performance.

A downside can be if you have an effect where the speed of what you’re moving changed (like a speed up/slow down boost), you’ll run into issues (which can be difficult to problem solve) having that variable cached. Unless the method being called is expensive, a lot say it’s often safer not to cache the variable. The other option that I see some people try to use to solve this issue is to have the WaveConfig call EnemyPathing to update the speed, but this creates a circular logic. While it’s not a big deal with a simple bit of coding like this, it’s a very bad habit to get into and will cause you more pain (in the future) than it’s worth.

Thanks. That was a very useful input!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms