Search code examples
c#arraysstringfunctionunity-game-engine

Function is not working, but gives no error


I'm new to C#. I'm trying to make game in Unity. These functions are necessary for changing in-game tabs with help of a button.

public string check;
public CanvasGroup hydrogenScreen;
public CanvasGroup heliumScreen;
private void EfficientTabChange(CanvasGroup group)
{
    string[] groupName = new string[2] { "hydrogenScreen" , "heliumScreen"};
    check = group.ToString();
    
    foreach (string nos in groupName)
    {
        
        if (check.Equals(nos))
        {
            ActivateTabs(group);
        }
        else
        {
            DeactivateTabs(group);
        }

    }
}
public void SwitchTabs(int id)
{
    switch (id)
    {
        case 0:
            EfficientTabChange(hydrogenScreen);
            break;
        case 1:
            EfficientTabChange(heliumScreen);
    }
}
private void ActivateTabs(CanvasGroup group)
{
    group.alpha = 1;
    group.interactable = true;
    group.blocksRaycasts = true;
}

private void DeactivateTabs(CanvasGroup group)
{
    group.alpha = 0;
    group.interactable = false;
    group.blocksRaycasts = false;
}

I don't know what is the problem in here. I'm just checking if the CanvasGroup is one of the names in array to find the right tab to change.


Solution

  • The main issue is you pass the same group to ActivateTabs(group); and DeactivateTabs(group); So, instead of using strings, compare the groups directly.

    private void EfficientTabChange(CanvasGroup group)
    {
        CanvasGroup [] groups = new CanvasGroup[2] { hydrogenScreen, heliumScreen };
        
        foreach (CanvasGroup g in groups)
        {
            if (g == group)
            {
                ActivateTabs(g);
            }
            else
            {
                DeactivateTabs(g);
            }
        }
    }