Can't activate empty GameObject with GameObject.Find and SetActive()

Hi, I’ve searched around a bit on the forum but can’t really find a solution to my problem. I have a canvas object with many text and button children (all as children of the canvas). I sorted these text objects and buttons into sub-categories with empty game objects for parents. Each set of buttons which should appear on screen at a given time is under an empty GameObject such as “Answers 1” and “Answers 2”. This script is attached to the Canvas.

I am using the

GameObject.find(“Canvas/Answers 1”);

referencing the empty GameObject which doesn’t work, and throws “NullReferenceException: Object reference not set to an instance of an object” at line 29 but:

GameObject.find(“Canvas/Answers 1/Q1A”);

works to activate the single button in the empty GameObject.
Each Answer set has four buttons, and there are 6 answer sets, so I find it inefficient to activate and deactivate 24 different buttons. They appear in sets of 4, so just activating 6 empty parent GamObjects of the answer sets would be much more efficient and make the code cleaner.

The empty GameObject(s) for the buttons are inactive in the scene and need to be activated.

I’ve also tried

GameObject.FindWithTag(“Answers 1”);

After tagging the empty GameObject with “Answers 1” with no effect.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.Experimental.UIElements;

public class QuestionChanger : MonoBehaviour {

 
    private GameObject btn1;
    //private GameObject btn2;
    //private GameObject btn3;
    //private GameObject btn4;
    private GameObject txt;
    //private Text txt2;
    //private Text txt3;
    //private Text txt4;
   // private Text txt5;
    //private Text txt6;


    // Use this for initialization
    void Start () {
  
        txt = GameObject.Find("Canvas/Text boxes/Question 1");
        txt.SetActive(true);
        //btn1 = GameObject.FindWithTag("Answers 1");
        btn1 = GameObject.Find("Canvas/Answers 1");
        btn1.SetActive(true);
   


    }
 
    // Update is called once per frame
    void Update () {
   
    }
}
1 Like

I can’t delete this thread, but I just want to say that I took a new approach to doing what I needed to do. Instead of activating and deleting different buttons, I’m just going to have 4 static buttons and one text element and changing the text on those Objects. Much simpler.

GameObject.Find only returns active game objects.
Threads can’t be deleted - just leave it here for the future. :slight_smile:

If you’ve already got a work around, that’s good. Another good way to have done it would be to reference your empty game objects in the inspector with drag and drop, and use said reference to enable/disable your groups :slight_smile: