U
U
Uncle Bogdan2021-09-26 09:50:54
Unity
Uncle Bogdan, 2021-09-26 09:50:54

How to make something normal out of such a system?

Created GridRepository:

public class StatisticRepository
{
    public int Coins;
}


And GridInteractor:

public class StatisticInteractor
{
    StatisticRepository _repository = new StatisticRepository();
    public int Coins => _repository.Coins;

    public delegate void OnCoinsValue();
    public event OnCoinsValue OnCoinsValueChanged;

    public void AddCoins(int value)
    {
        _repository.Coins += value;

        OnCoinsValueChanged?.Invoke();
    }

    public void SpentCoins(int value)
    {
        _repository.Coins -= value;

        OnCoinsValueChanged?.Invoke();
    }
}


Then I created a coin:

using UnityEngine;

public class Coin : MonoBehaviour
{
    [SerializeField] private int _value;
    [SerializeField] private ParticleSystem _effect;

    private StatisticInteractor _statisticInteractor = new StatisticInteractor();

    private void OnTriggerEnter(Collider other)
    {
        if(other.GetComponent<PlayerMovement>())
        {
            _statisticInteractor.AddCoins(_value);
            Instantiate(_effect, transform.position, Quaternion.identity);

            Destroy(gameObject);
        }
    }
}


And the problem is that each coin has its own number of coins. How to make it added to the "general" instance?

Then nothing is displayed in CoinsRender.

using UnityEngine;
using TMPro;

public class CoinsRender : MonoBehaviour
{
    [SerializeField] private TMP_Text _coinsText;

    StatisticInteractor _statisticInteractor = new StatisticInteractor();

    private void OnEnable()
    {
        _statisticInteractor.OnCoinsValueChanged += RenderText;
    }

    private void OnDisable()
    {
        _statisticInteractor.OnCoinsValueChanged -= RenderText;
    }

    public void RenderText()
    {
        _coinsText.text = "Монетки: " + _statisticInteractor.Coins;
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2021-09-26
@freeExec

Create StatisticInteractoronce, not every time. For example, as a static object. Google SingletonUnity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question