Question by
honeycombdesign · Mar 10, 2016 at 08:32 AM ·
c# tutorial
AddListener issue C#
I am not sure why it keeps telling me the onClick is not referred to. I am trying to understand.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class PuzzleGameController : MonoBehaviour {
[SerializeField]
private Sprite BgImage;
public Sprite[] puzzles;
public List<Sprite> gamePuzzles = new List<Sprite>();
public List<Button> btns = new List<Button>();
private bool firstGuess, secondGuess;
private int countGuesses;
private int countCorrectGuesses;
private int gameGuesses;
private int firstGuessIndex;
private int secondGuessIndex;
private string firstGuessPuzzle, secondGuessPuzzle;
void Awake()
{
puzzles = Resources.LoadAll<Sprite>("Sprite");
}
// Use this for initialization
void Start () {
GetButtons();
AddListeners();
AddGamePuzzles();
}
// Update is called once per frame
void Update () {
}
void GetButtons()
{
GameObject[] objects = GameObject.FindGameObjectsWithTag("LetterButton");
for (int i = 0; i < objects.Length; i++)
{
//add buttons to the grid
btns.Add(objects[i].GetComponent<Button>());
//change image on each button
objects[i].GetComponent<Image>().sprite = BgImage;
}
}
void AddListeners()
{
foreach (Button btn in btns)
{
btn.onClick.AddListener(() => PickAPuzzle());
}
}
void AddGamePuzzles()
{
int looper = btns.Count;
int index = 0;
//loop by how many buttons you have divide by 2 to make new row
for(int i = 0; i < looper; i++)
{
if(index == looper / 2)
{
index = 0;
}
gamePuzzles.Add(puzzles[index]);
index++;
}
}
public void PickAPuzzle()
{
string name = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name;
Debug.Log("Button Clicked " + name);
Debug.Log("first " + firstGuess);
Debug.Log("second " + secondGuess);
if (!firstGuess)
{
firstGuess = true;
Debug.Log(firstGuess);
//find index of button clicked on
firstGuessIndex = int.Parse(name);
Debug.Log("Button Clicked " + name);
Debug.Log(firstGuessIndex);
btns[firstGuessIndex].GetComponent<Image>().sprite = gamePuzzles[firstGuessIndex];
}
else if(!secondGuess){
secondGuess = true;
Debug.Log(secondGuess);
//find index of button clicked on
secondGuessIndex = int.Parse(name);
Debug.Log("Button Clicked " + name);
Debug.Log(secondGuessIndex);
btns[secondGuessIndex].GetComponent<Image>().sprite = gamePuzzles[secondGuessIndex];
}
}
}
Comment
At what line do you have the error? are you sure that GameObject[] objects = GameObject.FindGameObjectsWithTag("LetterButton");
is actually returning objects?