Home > Mobile >  Hide all tagged GameObjects upon button click
Hide all tagged GameObjects upon button click

Time:11-21

Trying to combine these two:

https://answers.unity.com/questions/1171111/hideunhide-game-object.html

Show/ hide Unity 3D elements

I got this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Modify_Menu_Button_Handler : MonoBehaviour
{

    void Start()
    {
        GameObject[] buttons_in_create_menu;
        buttons_in_create_menu = GameObject.FindGameObjectsWithTag("CreateMenu");
    }

    public void ChangeMenu()
    {
        foreach (GameObject button in buttons_in_create_menu)
        {
            button.SetActive(false);
        }
    }
}

But, the foreach line is red-underlined, saying the buttons_in_create_menu doesn't exist in the current context.

Coming from Javascript, I'm not sure how scope works in C# and especially within Unity's game loop. Thought the Start() function would be called upon the scene loading, based on the Unity docs: link

CodePudding user response:

You must define the variable globally in the class.

Like this:

public class Modify_Menu_Button_Handler : MonoBehaviour
{
    public GameObject[] buttons_in_create_menu;
    void Start()
    {
        buttons_in_create_menu = GameObject.FindGameObjectsWithTag("CreateMenu");
    }

    public void ChangeMenu()
    {
        foreach (GameObject button in buttons_in_create_menu)
        {
            button.SetActive(false);
        }
    }
}
  • Related