Reputation: 459
I just started a unity project for some basic game stuff.
This might be wrong question or invalid process.
I have done hide/show panel on button click, Now I want to hide/show after value change of dropdown.
I have two panel, one for basic info and other for security info. And after select dropdown value I want to display one of these panel and hide second panel.
But I have no idea how to achieve that.
I am tring some basic logic and stuck on that.
What I did:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
public class WithrowModalPanel : MonoBehaviour
{
public Button cancelButton;
public GameObject modalPanelObject;
public GameObject modalPanelObjectAdvance;
public Dropdown myDropdown;
private static WithrowModalPanel modalPanel;
public static WithrowModalPanel Instance()
{
if (!modalPanel)
{
modalPanel = FindObjectOfType(typeof(WithrowModalPanel)) as WithrowModalPanel;
if (!modalPanel)
Debug.LogError("There needs to be one active ModalPanel script on a GameObject in your scene.");
}
return modalPanel;
}
void Update()
{
switch (myDropdown.value)
{
case 1:
Debug.Log("Basic panel!");
modalPanelObject.SetActive(true);
modalPanelObjectAdvance.SetActive(false);
break;
case 2:
Debug.Log("Advance panel!");
modalPanelObjectAdvance.SetActive(true);
modalPanelObject.SetActive(false);
break;
}
}
}
I just stared unity and didnt have much idea about its structure.
Upvotes: 0
Views: 2071
Reputation: 90749
Note that Dropdown.value
is 0-base indexed so the first entry is 0
not 1
. I don't know your complete setup but I guess that was the main issue in your attempt.
Then Dropdowns have an event onValueChanged
instead of doing it in Update
you should rather register a listener to it
private void Start()
{
// Just to be sure it is always only added once
// I have the habit to remove before adding a listener
// This is valid even if the listener was not added yet
myDropdown.onValueChanged.RemoveListener(HandleValueChanged);
myDropdown.onValueChanged.AddListener(HandleValueChanged);
}
private void OnDestroy()
{
// To avoid errors also remove listeners as soon as they
// are not needed anymore
// Otherwise in the case this object is destroyed but the dropdown is not
// it would still try to call your listener -> Exception
myDropdown.onValueChanged.RemoveListener(HandleValueChanged);
}
private void HandleValueChanged(int newValue)
{
switch (newValue)
{
case 0:
Debug.Log("Basic panel!");
modalPanelObject.SetActive(true);
modalPanelObjectAdvance.SetActive(false);
break;
case 1:
Debug.Log("Advance panel!");
modalPanelObjectAdvance.SetActive(true);
modalPanelObject.SetActive(false);
break;
}
}
Hint: you could use the generic of FindObjectOfType
modalPanel = FindObjectOfType<WithrowModalPanel>();
Upvotes: 1