Question by
skillitronic · Mar 08, 2021 at 10:04 PM ·
uiupdatesynchronization
How to update ui in unity properly
I can't find best way on how to update the UI in Unity like a good developer would.
For example: I have a card which contains: - card name - manacost - card desc - damage
I created scriptable object script to store data about name,desc,damage.
[CreateAssetMenu(menuName = "Create card", fileName = "new Card")]
public class CardScriptableObject : ScriptableObject
{
public string CardName
{
get => _cardName;
}
public string Description
{
get => _description;
}
public int ManaCost
{
get => _manacost;
}
public int Damage
{
get => _damage;
}
public int Health
{
get => _health;
}
[SerializeField] private string _cardName;
[SerializeField] private string _description;
[Min(1)] [SerializeField] private int _manacost;
[Min(0)] [SerializeField] private int _damage;
[Min(0)] [SerializeField] private int _health;
}
Also I created card script which will use local variable of this name,desc,damage to use in project.
[DisallowMultipleComponent]
public class Card : MonoBehaviour
{
[SerializeField] private CardScriptableObject _cardData;
[SerializeField] private CardDisplay _cardDisplay;
public int Health
{
get => _health;
set
{
_health = value;
if (_health <= 0)
Die();
}
}
public int Damage
{
get => _damage;
private set
{
if (value < 0)
value = 0;
_damage = value;
}
}
public int ManaCost
{
get => _manaCost;
private set
{
if (value < 0)
value = 0;
_manaCost = value;
}
}
private int _damage;
private int _manaCost;
private int _health;
private void Awake()
{
_health = _cardData.Health;
}
private void Die()
{
Debug.Log("Card destroyed");
}
}
And I created card display script which will link UI objects with variables.
[DisallowMultipleComponent]
public class CardDisplay : MonoBehaviour
{
[SerializeField] private CardScriptableObject cardData;
[SerializeField] private Image cardArtImage;
public TextMeshProUGUI HealthText
{
get => _healthText;
}
public TextMeshProUGUI DamageText
{
get => _damageText;
}
public TextMeshProUGUI ManaCostText
{
get => _manaCostText;
}
[SerializeField] private TextMeshProUGUI _healthText;
[SerializeField] private TextMeshProUGUI _damageText;
[SerializeField] private TextMeshProUGUI _manaCostText;
}
Now I want to know how to Update UI in unity when card will Instantiated,Changed health value.
Maybe use events?
Implement in setter (i think its not a good thing)?
Create something like UIManager?
It would be nice if someone gave me a links on how to do it in a good way. Or give me an example of how you would do it.
Comment