Custom Class - What did I do wrong?
Hello everyone. I'm currently trying to make a very simple practice game for mobile, with several pop up menus that the player has the ability to open/close. I could technically keep using and renaming two SetActive() commands and keep adding GameObjects to my Game Manager script like so:
[SerializedField] GameObject _popUp;
public void Open()
{
_popUp.SetActive(true);
}
public void Close()
{
_popUp.SetActive(false);
}
But that feels redundant, surely there can be a way where can create a custom class and then just reference it as an array in GameManager.cs, so here's what I came up with:
[Serializable]
public class PopUpSystem
{
[SerializeField] GameObject window;
[SerializeField] Button open;
[SerializeField] Button close;
private void Open()
{
window.SetActive(true);
}
private void Close()
{
window.SetActive(false);
}
}
This way I can fill out the necessary information in the inspector without cluttering up my code. However I must've done something wrong since neither of my buttons seem to work. I am a beginner so I probably made some mistake, in any case if anyone could help me understand what I did wrong that would be great.
EDIT: I figured it out, there's probably a way to optimize this method but it works for now:
public class GameManager : MonoBehaviour
{
[Serializable]
public class PopUpSystem
{
[SerializeField] public GameObject window;
[SerializeField] public Button open;
[SerializeField] public Button close;
public void Open()
{
window.SetActive(true);
}
public void Close()
{
window.SetActive(false);
}
}
[SerializeField] PopUpSystem[] popUps;
private void OnEnable()
{
for ( int i = 0; i < popUps.Length; i++ )
{
popUps[i].open.onClick.AddListener((popUps[i].Open));
popUps[i].close.onClick.AddListener((popUps[i].Close));
}
}
}