Problem with an array of gameobjects

Hi, i have an array of gameobjects that is filled with every gameobject that has the tag “HookPoint”. Every gameobject of the array has a script with OnMouseOver function that turns to true a bool variable (when the mouse is over the object the variable is true and turns false OnMouseExit)
I want that the bool variable of the script witht he array turns true when at least one of the objects in the array has the variable true and that it turns false if every object has the bool variable set to false.
This variable is called CanHook in the script with the array and in the one of every gameobject witht he OnMouseOver function.
The probelm is that the variable turns true only if i put the cursor on the last element of the array.
Do anyone know how to fix it?

Hi there,

In future when posting scripting questions, you should copy your code into your post, using code tags (there’s a stickied post on this forum that shows how to do so).

Nonetheless, a few things to note. You have a for loop that loops through all HookPoints… then a foreach loop that does the same thing. This isn’t necessary; you only need either the for loop, or the foreach loop.

Even then, I don’t think fixing this will fix the behaviour you’re experiencing. Because you’re going over everything you find every frame, CanHook will only remain true for the frame if you mouse over the last result.

So if you only care about one point being true, then you want to exit the loop when you hit a positive result. Like so:

private void Update()
{
   foreach (GameObject go in HookPoints)
   {
       if (go.GetComponent<HookPoint>().CanHook == true)
       {
           CanHook = true;
           break;
       }  
   }
  
   CanHook = false;
}

break will exit the loop early, so once you assign CanHook to true it will remain true. If it makes it through the collection with no hits, then CanHook is assigned false at the end. The code can further made safer mind you, as if you hit anything with this “HookPoint” tag that doesn’t have the HookPoint component, you’ll run into a null reference error. So you get all the components instead:

public class GetHookPoint : Monobehaviour
{
    private HookPoint[] HookPoints;

    private bool CanHook = false;

    private void Start()
    {
        HookPoints = FindObjectsOfType<HookPoint>(); //instead we get references to all HookPoint components
    }
  
    private void Update()
    {
        foreach (HookPoint point in HookPoints)
        {
            if ((CanHook = point.CanHook) == true) //here we both assign and check the value of CanHook, and break if true
                break;
        }
    }
}

Now of course this isn’t a very efficient method but hopefully explains a few things.

Additionally I see your Visual Studio isn’t properly set up as none of the Unity classes are highlighted properly. You may want to search up ways to fix that and make your experience coding that much better.