How to trigger picking up objects of a certain tag?

I'm developing a unity searching game, where the player should look for certain objects. The target objects are tagged as "TargetObj". The player should win when he picks up all objects with that tag. So if there are two objects with the tag "TargetObj", the player should pick up the first one and release it and then when he picks up the second one he wins (because he picked up all targeted objects).

Here is what I tried to do to achieve this:

         GameObject[] targetObjects;
            List<GameObject> targetObjectsList;
      private void Start()
            {
        
                mainCamera = Camera.main;
                targetObjects = GameObject.FindGameObjectsWithTag("TargetObj");
                targetObjectsList = new List<GameObject>();  
            }
 if (Input.GetKeyDown(KeyCode.Space))
        {
            //and we're not holding anything
            if (currentlyPickedUpObject == null)
            {
                //and we are looking an interactable object
                if (lookObject != null )
                {
                    PickUpObject();            
                    if (!targetObjectsList.Contains(lookObject.gameObject))
                    {
                        targetObjectsList.Add(lookObject.gameObject);

                        if (targetObjectsList.Count == targetObjects.Length) 
                        {

                            winUI.SetActive(true);
                            Time.timeScale = 0f;
                            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
                          //Time.timeScale = 1f;
                        }
                    }

Here is my full code:

public class PlayerInteractions : MonoBehaviour
{
    GameObject[] targetObjects;
    List<GameObject> targetObjectsList;
    [Header("InteractableInfo")]
    public float sphereCastRadius = 0.5f;
    public int interactableLayerIndex;
    private Vector3 raycastPos;
    public GameObject lookObject; 
    private PhysicsObjects physicsObject;
    private Camera mainCamera;
    public GameObject winUI;
    private InteractiveObjects interactiveObjects;
    [Header("Pickup")]
    [SerializeField] private Transform pickupParent;
    public GameObject currentlyPickedUpObject;
    private Rigidbody pickupRB;
    [Header("ObjectFollow")]
    [SerializeField] private float minSpeed = 0;
    [SerializeField] private float maxSpeed = 300f;
    [SerializeField] private float maxDistance = 3.5f;
    private float currentSpeed = 0f;
    private float currentDist = 0f;
    [Header("Rotation")]
    public float rotationSpeed = 100f;
  //  Quaternion lookRot;
    [SerializeField] GameObject TargetsCanvas;
    static bool strikeThrough = false; 
 private void Start()
    {

        mainCamera = Camera.main;
        targetObjects = GameObject.FindGameObjectsWithTag("TargetObj");
        targetObjectsList = new List<GameObject>();
        foreach (var obj in targetObjects)
        {
            var mytext = CreateText(TargetsCanvas.transform);
            mytext.text = "• Find The " + obj.name;
            Debug.Log(""+ obj.name); 
       }
        
    }
  void Update()
    {
        //Here we check if we're currently looking at an interactable object
        raycastPos = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
        RaycastHit hit;
        if (Physics.SphereCast(raycastPos, sphereCastRadius, mainCamera.transform.forward, out hit, maxDistance, 1 << interactableLayerIndex))
        {
           
            lookObject = hit.collider.transform.gameObject;
        }
        else 
        {
            lookObject = null; 
        }
 if (Input.GetKeyDown(KeyCode.Space))
        {
            //and we're not holding anything
            if (currentlyPickedUpObject == null)
            {
                //and we are looking an interactable object
                if (lookObject != null )
                {
                    PickUpObject();            
                    if (!targetObjectsList.Contains(lookObject.gameObject))
                    {
                        targetObjectsList.Add(lookObject.gameObject);

                        if (targetObjectsList.Count == targetObjects.Length) 
                        {
                            
                            winUI.SetActive(true);
                            Time.timeScale = 0f;
                            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
                          //Time.timeScale = 1f;
                        }
                    }
                   
                }    
            }
            //if we press the pickup button and have something, we drop it
            else
            {
                BreakConnection();
            }
        }

 private void FixedUpdate()
    {
        if (currentlyPickedUpObject != null)
        {
            currentDist = Vector3.Distance(pickupParent.position, pickupRB.position);
            currentSpeed = Mathf.SmoothStep(minSpeed, maxSpeed, currentDist / maxDistance);
            currentSpeed *= Time.fixedDeltaTime;
            Vector3 direction = pickupParent.position - pickupRB.position;
            pickupRB.velocity = direction.normalized * currentSpeed;
        }
    }
    //Release the object 
    public void BreakConnection()
    {
        pickupRB.constraints = RigidbodyConstraints.None;
        currentlyPickedUpObject = null;
        lookObject = null;
        physicsObject.pickedUp = false;
        currentDist = 0;
    }
    public void PickUpObject()

    {
        physicsObject = lookObject.GetComponentInChildren<PhysicsObjects>();
        currentlyPickedUpObject = lookObject;
        pickupRB = currentlyPickedUpObject.GetComponent<Rigidbody>();
        pickupRB.constraints = RigidbodyConstraints.FreezeRotation;
        physicsObject.playerInteractions = this;
    }

However, my code doesn't work as it is supposed to, currently, if I have 2 objects with the tag "targetObj" and the player picked up any two objects he wins!! regardless of their tags.

can somebody help me figure out what's wrong here? please help.


Solution 1:

well your pickup method doesn't check whether the object you are looking at actually is tagged correctly. So you could be adding any object(s) from the interactable Layer.

You should probably add a check like e.g.

private void Update()
{
    ...

    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (currentlyPickedUpObject == null)
        {
            if(lookObject != null)
            {
                PickUpObject();
                
                // check if the lookObject actually has the correct tag
                if(lookObject.CompareTag("TargetObj") && !targetObjectsList.Contains(lookObject))
                {
                    targetObjectsList.Add(lookObject);

                    ...
                }
            }
        }
        else
        {
            ...
        }
    }
}