How can I implement an objective system?

Hi guys! First time posting on the forum.

Some friends and I are making a walking simulator and I’m having doubts about how I can implement an objective system (such as going to X place, take an object … The typical).

As in many games the idea is that the objectives are shown in a HUD that the player can show and hide, where the player’s current objective will be shown, and when a task is completed, it will be crossed out (it doesn’t disappear from the HUD) and below it will appear the new one.

I’ve been watching some videos and posts in the forum and I still don’t see how to implement it. I don’t know if using triggers is the best option, and how can I make the objectives appear one below the other (I could use a list of Text objects?).

Hope I make my self clear and thank you very much in advance!

First you need to define what objective types you want to have, because each one would have different needs and implementation, for example “Go to point” would just need a Vector3 position, or just a GameObject (with a Trigger Collider or plain distance check), while a “Kill an enemy” need to have a reference to an enemy GameObject with an Enemy script where we can check its health/dead status.

Generally you want to use an interface here that all objective types need to implement, something like (code not tested, but you should get the idea):

public interface IObjective
{
    string Title { get; }
    string Description { get; }
    bool IsCompleted { get; }
}

// Attach this script to a GameObject you want it to become a GoToObjective
public class GoToObjective : MonoBehavior, IObjective
{
    [SerializedField]
    private string title;
    [SerializedField]
    private string description;
    [SerializedField]
    private Transform playerTransform;

    public string Title => title;
    public string Description => description;
    public bool IsCompleted { get; private set; }

    private void Start()
    {
        // Add the objective to an ObjectivesManager (Singleton) that holds a
        // List<IObjective> that you can read to get all Objectives (or remaining ones)
        // and display them on the UI

        ObjectivesManager.Instance.AddObjective(this);
    }

    private void Update()
    {
        CheckCompleted();
    }

    private void CheckCompleted()
    {
        if (IsCompleted)
            return;

        if (Vector3.Distance(playerTransform.position, transform.position) < 0.25f))
        {
            IsCompleted = true;
            ObjectivesManager.Instance.SetObjectiveCompleted(this);
        }
    }
}

// Attach this script to a GameObject you want it to become a KillEnemyObjective
// The GameObject should also have an Enemy script attached so we can check if its dead.
public class KillEnemyObjective : MonoBehavior, IObjective
{
    [SerializedField]
    private string title;
    [SerializedField]
    private string description;

    private Enemy enemy;

    public string Title => title;
    public string Description => description;
    public bool IsCompleted { get; private set; }

    private void Awake()
    {
        enemy = GetComponent<Enemy>();

        // Or just add [RequireComponent(typeof(Enemy)] before the class declaration
        if (enemy == null)
            throw Exception("This Objective requires an Enemy script in the same GameObject");
    }

    private void Start()
    {
        // Add the objective to an ObjectivesManager (Singleton) that holds a
        // List<IObjective> that you can read to get all Objectives (or remaining ones)
        // and display them on the UI

        ObjectivesManager.Instance.AddObjective(this);
    }

    private void Update()
    {
        CheckCompleted();
    }

    private void CheckCompleted()
    {
        if (IsCompleted)
            return;

        if (enemy.Health <= 0)
        {
            IsCompleted = true;
            ObjectivesManager.Instance.SetObjectiveCompleted(this);
        }
    }
}

// You notice that both Objective scripts share a lot of code, like adding the objective
// to the ObjectivesManager or calling CheckCompleted on Update, in this case
// you can create a base abstract Objective class that all Objectives inherit from like this:
public abstract class Objective : MonoBehavior, IObjective
{
    [SerializedField]
    private string title;
    [SerializedField]
    private string description;
 
    public string Title => title;
    public string Description => description;
    public bool IsCompleted { get; private set; }

    protected virtual void Start()
    {
        // Add the objective to an ObjectivesManager (Singleton) that holds a
        // List<IObjective> that you can read to get all Objectives (or remaining ones)
        // and display them on the UI

        ObjectivesManager.Instance.AddObjective(this);
    }

 
    protected virtual void Update()
    {
        CheckCompleted();
    }

    private void CheckCompleted()
    {
        if (IsCompleted)
            return;

        if (IsObjectiveCompleted())
        {
            IsCompleted = true;
            ObjectivesManager.Instance.SetObjectiveCompleted(this);
        }
    }

    protected abstract bool IsObjectiveCompleted();
}

// Then your Objectives would simply become:
public GoToObjective : Objective
{
    [SerializedField]
    private Transform playerTransform;

    protected override bool IsObjectiveCompleted()
    {
        return Vector3.Distance(playerTransform.position, transform.position) < 0.25f;
    }
}


public KillEnemyObjective : Objective
{
    private Enemy enemy;

    private void Awake()
    {
        enemy = GetComponent<Enemy>();

        // Or just add [RequireComponent(typeof(Enemy)] before the class declaration
        if (enemy == null)
            throw Exception("This Objective requires an Enemy script in the same GameObject");
    }

    protected override bool IsObjectiveCompleted()
    {
        return enemy.Health <= 0;
    }
}

// Attach this script to an empty GameObject in your Scene
public class ObjectivesManager : MonoBehavior
{
    private readonly List<IObjective> _objectives = new();

    // An event that is raised when an objective is completed
    // (maybe play a sound, or an effect, or update the UI to mark it as completed...)
    public event Action<Objective> ObjectiveCompleted;

    public static ObjectivesManager Instance { get; private set; }

    // This is our Objectives list. Use this to iterate over all Objectives and display them in UI
    public IReadOnlyList<IObjective> Objectives => _objectives;

    public void AddObjective(IObjective objective)
    {
        // Sanity check
        if (objective == null)
            throw new NullReferenceException(objective);

        // We make sure we're not adding an already added objective
        if (!_objectives.Contains(objective))
            _objectives.Add(objective);
    }

    public void SetObjectiveCompleted(IObjective objective)
    {
        // Sanity checks
        if (objective == null)
            throw new NullReferenceException(objective);

        if (!objective.IsCompleted)
            throw new Exception($"Objective {objective} is not completed yet!");

        ObjectiveCompleted?.Invoke(objective);
    }

    private void Awake()
    {
         // Singleton pattern, only one can live in a Scene
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);
    }
}

OnGUI isn’t very popular these days but it may help you to get up and running:

   public GameObject[] objectives;     // Add triggers to this array. Disable the objects when triggered/completed.

   void OnGUI()
   {
      GUI.skin.label.fontSize = 16;
      GUI.Box(new Rect(10, 10, 400, 300),"");
      GUILayout.BeginArea(new Rect (20, 20, 400, 300));
      foreach (GameObject obj in objectives)
      {
         if (obj.activeSelf)        // mission active?
            GUI.color=Color.white;
         else
            GUI.color=Color.gray;
         GUILayout.Label(obj.name);      // GameObject's name holds the mission description
      }
      GUILayout.EndArea();
   }

Just so you know, “watching some videos” is actually NEVER going to be a useful way to learn gamedev.

Try this simple two-step process instead:

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.