Search code examples
c#unity-game-engineunity3d-gui

GameObject prefab is not showing in scene when activated in my script


I have 2 classes attached to 2 different GUIs, PlayerInfoGUI and DiplomacyGUI.

I am trying to have a method in PlayerInfoGUI create a list of buttons dynamically which, when clicked will then pull up DiplomacyGUI. (Both GUIs as well as the dynamic buttons have their own prefabs created)

My PlayerInfoGUI class dynamically populates a panel with buttons using the PopulatePlayerList method.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;


public class PlayerInfoGUI : MonoBehaviour
{
    public Image[] guiElements;
    public GameObject playerInfoButtonPrefab, canvasParent;
    public GameObject diplomacyMenu;

    void Awake ()
    {
        PopulatePlayerList (GameEngine.competingPlayers);
    }

    void PopulatePlayerList (List<CompetingPlayer> players)
    {

        for (int i = 0; i < players.Count; i++) {
            GameObject go = (GameObject)Instantiate 
            (playerInfoButtonPrefab);
            Button playerInfoButton = go.GetComponent<UnityEngine.UI.Button> 
                                                                         ();
            CompetingPlayer receivingPlayer = players [i];
            playerInfoButton.onClick.AddListener (() => handleDiplomacyMenu 
                                                         (receivingPlayer));
            go.transform.SetParent (canvasParent.transform, false);
        }
    }

    public void handleDiplomacyMenu (CompetingPlayer receivingPlayer)
    {
        diplomacyMenu.SetActive (true);
    }
}

The listener on the PlayerInfo Button is firing when clicked, but the diplomacyMenu GameObject is not showing up in the scene. Most of the research I have read says this should be a simple diplomacyMenu.SetActive(true), or a diplomacy.gameObject.SetActive(true), but this doesn't work.

I have confirmed that the code is being run, but the object cannot be seen. Thank you in Advance!

PlayerInfoPrefab

PlayerInfoButtonPrefab

DiplomacyPrefab


Solution

  • You're using diplomacyMenu.gameObject when diplomacyMenu is already a game object, this might cause issues. Also make sure the prefab that is represented by diplomacyMenu has its children enabled. I think SetActive() just sets the top level parent to enabled, not any nested objects.