In one of my loops which I use to change the settings of my buttons, I also use the AddListener function rather then the one in the Inspector. I have 5 items, giving a range of "i" from 0-4, but when I print "i" trough the function it should call, it always logs 5, no matter what button I press, which is weird since "i" never even reaches 5. Any idea?
P.s. I use a CustomEditor to show the 2 buttons "Preview Layout" and "Delete Preview" in the inspector.
Code:
using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;
public class RateMeManager : MonoBehaviour {
public GameObject rateMeCanvas;
public Sprite emptyStar, fullStar, button;
public float spriteWidth, spriteHeight, spritePadding;
[HideInInspector]
public GameObject currentCanvas, tempButton;
void Start () {
RemovePreview();
GenerateStars();
}
// Update is called once per frame
public void GenerateStars () {
RectTransform myRectTransform;
if (currentCanvas != null)
{
GameObject temp;
temp = currentCanvas;
DestroyImmediate(temp);
}
currentCanvas = Instantiate(rateMeCanvas, Vector3.zero, Quaternion.identity) as GameObject;
GameObject subCanvas = currentCanvas.transform.FindChild("subCanvas").gameObject;
myRectTransform = subCanvas.GetComponent<RectTransform>();
myRectTransform.sizeDelta = new Vector2((5*spriteWidth) + (4*spritePadding), spriteHeight);
myRectTransform.anchoredPosition = Vector2.zero;
Button[] buttons = subCanvas.GetComponentsInChildren<Button>();
float[] positions = new float[] {((2*spriteWidth)+(2*spritePadding))*-1, ((1 * spriteWidth) + (1 * spritePadding)) * -1 , 0, ((1 * spriteWidth) + (1 * spritePadding)), ((2 * spriteWidth) + (2 * spritePadding))};
for (int i = 0; i < buttons.Length; i++)
{
Debug.Log(i);
tempButton = buttons[i].gameObject;
tempButton.GetComponent<Button>().image.sprite = emptyStar;
myRectTransform = buttons[i].GetComponent<RectTransform>();
myRectTransform.sizeDelta = new Vector2(spriteWidth, spriteHeight);
myRectTransform.anchoredPosition = new Vector2(positions[i], 0);
tempButton.GetComponent<Button>().onClick.AddListener(() => OnGivenRate(i));
}
}
public void RemovePreview()
{
DestroyImmediate(currentCanvas);
}
private void OnGivenRate(int stars)
{
Debug.Log("pressed star: " + stars);
}
public class RateMeEditor
{
[CustomEditor(typeof(RateMeManager))]
public class button : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
RateMeManager myScript = (RateMeManager)target;
if (GUILayout.Button("Preview Layout"))
{
myScript.GenerateStars();
}
if (GUILayout.Button("Delete Preview"))
{
myScript.RemovePreview();
}
}
}
}
}