Menu for change Quality in runtime: Button.onClick.AddListener?

Hi, I wanted to use the following code to change the game quality with a script that takes the available qualities and transforms them in a runtime dropdown menu

It was wrote first in a unity project, whose only purpose is testing things, and it works.

But, when placed in another project that has a game in, it produces on red line the error CS1061: Type Button' does not contain a definition for onClick’ and no extension method onClick' of type Button’ could be found (are you missing a using directive or an assembly reference?)

I don`t understand why the same script gives error in one file and not in another, and it would be awesome if the UI script documentation had more examples

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//using UnityEngine.Events;
//using UnityEngine.EventSystems;

public class QualityMenu : MonoBehaviour
{
string [ ] qualityNames;

public GameObject buttonPrefab;
public Transform qualityButtonsPanel;

void Start ()
{
qualityNames = QualitySettings.names;

CreateQualityMenu ();
}

void CreateQualityMenu ()
{
for (int i = 0; i < qualityNames.Length; i++)
{
GameObject button = Instantiate (buttonPrefab) as GameObject;
button.GetComponentInChildren ().text = qualityNames ;
int qualityIndex = i;
button.GetComponent ().onClick.AddListener
(
() => {SetQuality (qualityIndex);}
);
button.transform.SetParent (qualityButtonsPanel, false);
}
}
public void SetQuality (int index)
{
QualitySettings.SetQualityLevel(index, false);
}
}

Solved: it must be some Button class that is overlapping with the Button in the project I am working on

Found here: error CS0426: The nested type `ButtonClickedEvent' does not exist in the type `Button' - Questions & Answers - Unity Discussions

The new code would be:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//using UnityEngine.Events;
//using UnityEngine.EventSystems;

public class QualityMenu : MonoBehaviour
{
string [ ] qualityNames;

public GameObject buttonPrefab;
public Transform qualityButtonsPanel;

void Start ()
{
qualityNames = QualitySettings.names;

CreateQualityMenu ();
}

void CreateQualityMenu ()
{
for (int i = 0; i < qualityNames.Length; i++)
{
GameObject button = Instantiate (buttonPrefab) as GameObject;
button.GetComponentInChildren ().text = qualityNames ;
int qualityIndex = i;
UnityEngine.UI.Button btn = button.GetComponent <UnityEngine.UI.Button> ();
btn.onClick.AddListener
(
() => {SetQuality (qualityIndex);}
);
button.transform.SetParent (qualityButtonsPanel, false);
}
}
public void SetQuality (int index)
{
QualitySettings.SetQualityLevel(index, false);
}
}

1 Like

Thank you!