Hi guys,
I try to call a function from another script with a button, but unity throws an error when i click one of the items (not before).
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
public class Wardrobe : MonoBehaviour {
public Material[] materialSkinColor;
public Material[] materialHaircuts;
public Material[] materialEyes;
public Material[] materialTop;
public Material[] materialBottom;
public Material[] materialShoes;
public Sprite[] previewSkinColor;
public Sprite[] previewHaircuts;
public Sprite[] previewEyes;
public Sprite[] previewTop;
public Sprite[] previewBottom;
public Sprite[] previewShoes;
public RectTransform listContainer;
public GameObject playerMesh;
Clothes clothesScript;
Material[] clothes;
Sprite[] previews;
void Start()
{
clothesScript = playerMesh.GetComponent<Clothes>();
Populate("skin color");
}
public void Populate(string bodypart)
{
var children = new List<GameObject>();
foreach (Transform child in listContainer.transform) children.Add(child.gameObject);
children.ForEach(child => Destroy(child));
listContainer.anchoredPosition = Vector3.zero;
switch (bodypart)
{
case "skin color":
previews = previewSkinColor;
clothes = materialSkinColor;
break;
case "haircut":
previews = previewHaircuts;
clothes = materialHaircuts;
break;
case "eyes":
previews = previewEyes;
clothes = materialEyes;
break;
case "top":
previews = previewTop;
clothes = materialTop;
break;
case "bottom":
previews = previewBottom;
clothes = materialBottom;
break;
case "shoes":
previews = previewShoes;
clothes = materialShoes;
break;
default:
break;
}
Debug.Log(previews.Length + " - " + clothes.Length); // shows same length
for (int i = 0; i < previews.Length; i++)
{
GameObject listItem = new GameObject();
Image img = listItem.AddComponent<Image>();
img.sprite = previews[i];
Button btn = listItem.AddComponent<Button>();
btn.onClick.AddListener(() => { clothesScript.Set(bodypart, clothes[i]); });
listItem.transform.parent = listContainer.transform;
}
}
}
The error is on the onClick.Addlistener line.
I’ve tried to call another function from clothesScript (.Test()) that only contains a Debug.Log and it works fine. The problem is only an index array, but the line Debug.Log(previews.Length + " - " + clothes.Length); shows the same values.
Can you help me find out why ? Thanks.