Collect object in a correct order

Hey gentlemen,

I have a little code to write but I am not sure how to do it.

Basically, I have 3 objects to pickup and I need to pick them up in order, let’s simply say from 1 to 3.

If I pick the correct object in the order nothing will happen just keep playing.
Instead if I pick Up the third object rather then the first the player will die.

do you have any universal code idea for this?

thanks

You could add your ‘target’ objects to a list in numerical order [target1, target2, target3]. When you attempt to pick-up a target object do the following…

  1. If the target object list index equals 0, remove it from the list and continue
  2. If the target object list index does not equal 0 the player is eliminated

Example Code

using UnityEngine;
using System.Collections.Generic;

public class TargetHandler : MonoBehaviour {
    // Public References
    public List<Transform> targetCache; // Add Target Objects In Inspector

    // --
    void OnTriggerEnter(Collider col) {
        // Identify Collision Object
        if (targetCache.Contains(col.transform)) {
            if (targetCache.IndexOf(col.transform) == 0) {
                // Debug Message
                print("Pickup Collected");
                // Remove Target Object From List
                targetCache.RemoveAt(0);
                // >> Your Pickup Code Here <<
            }
            else {
                // Debug Message
                print("Player Eliminated");
                // Your Eliminate Player Code Here <<
            }
        }
    }
}
1 Like

That’s awesome. But it looks like it refers only for the element 0 of the list. Doesn’t it mean that once I pick up the first object the function will still check the element 0 while the second object is in the index 1?

Another thing I’m not sure about are those condition inside the if. I have a player with tag “Player” that I guess I should use it as a collision identifier is it right ? How should I write it ?

Hi

As the collision removes the first target object from the list, the next available target object will be assigned index 0. This will continue until the list is empty.

Keep in mind that the list index refers to the position of the object in the list as opposed to the name of the game object.

For example, the script would be attached to the ‘Player’ object. When a collision is detected (in this case a trigger) the script checks if the col.transform exists in the ‘targetCache’ list. No object tags are required.

How you configure the script will depend on your specific project.

problem solved. thanks a lot

1 Like