A
A
Artemy2020-04-29 13:12:42
C++ / C#
Artemy, 2020-04-29 13:12:42

Why are my buttons not working?

I wanted to try to make a solution that would allow me not to write a separate code for each product. As planned, to create a new product, there should be enough work in the editor, and the code can be left alone.

But, I would not write this if the code worked. And the code does nothing at all. What was wrong?

Screenshot of the editor
5ea950d6e4c05667750753.png

using System;
using UnityEngine;
using UnityEngine.UI;

public class Shop : MonoBehaviour
{
    public GameObject storefront;//витрина
    public Sprite[] numbers;//ссылки на img для рисованых чисел
    public Button[] goods;//кнопки товаров
    int[] goodsCounter;//счётчик для рисованых чисел
    int coins = 0;
    void Start()
    {
        if (PlayerPrefs.HasKey("Coins"))
            coins = PlayerPrefs.GetInt("Coins");
        //загружаем информацию по наличию продаваемых предметов
        for (int i = 0; i < goods.Length; i++)
        {
            if (PlayerPrefs.HasKey(goods[i].name))
            {
                goodsCounter[i] = PlayerPrefs.GetInt(goods[i].name);
                goods[i].transform.GetChild(0).transform.GetChild(0).GetComponent<Image>().sprite = numbers[goodsCounter[i]];
                print(goodsCounter[i]);
            }
            else
            {
                goodsCounter[i] = 0;
                PlayerPrefs.SetInt(goods[i].name, 0);
            }
        }
    }
    public void BuyTheItem(int index) //для покупки достаточно указать в редакторе номер товара
    {
        index--;
        if (coins >= Convert.ToInt32(goods[index].transform.GetChild(1).GetComponent<Text>().text))
        {
            goodsCounter[index]++;
            PlayerPrefs.SetInt(goods[index].name, goodsCounter[index]);
            PlayerPrefs.SetInt("Coins", coins - Convert.ToInt32(goods[index].transform.GetChild(1).GetComponent<Text>().text));
            goods[index].transform.GetChild(0).transform.GetChild(0).GetComponent<Image>().sprite = numbers[goodsCounter[index]];
        }
    }
}

OnClick()
5ea950fa284f8801748572.png

PS And I will be grateful if you tell me a normal title for this question ^^"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artemy, 2020-04-29
@Artemonim

The problem is that I forgot how to work with dynamic arrays. Unity cursed that the problem was NullPointer, and I forgot to check the console.
He brought the console to a prominent place, and fixing int[] on List solved the problem

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question