I am making a drag and drop inventory system with a hotbar. This script ItemPanelHelper will help distinguish between new items with an image, item name, and item count. It will/does reset the image, highlight item being selected, swap out data, and set new data.
Instead of using legacy Unity UI text I opted to us Text Mesh Pro. For some reason when I enter play mode my itemName and itemCount don't clear out. Am I correctly accessing the TMP text? Any feedback is welcome! This is what I have so far. It works with Unity's Legacy UI text.
Above: item count: 999 and item name: "BIG SHINY" both should clear out when in play mode.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ItemPanelHelper : MonoBehaviour
{
public Action<int, bool> OnClickEvent;
public Image itemImage;
[SerializeField]
private TextMeshProUGUI nameText, countText; // here I switched out Text with TextMeshProUGUI
public string itemName, itemCount;
public bool isEmpty = true;
public Outline outline; // indicates if item is selected
public bool isHotbarItem = false;
public Sprite backgroundSprite;
private void Start()
{
outline = GetComponent<Outline>();
outline.enabled = false;
if(itemImage.sprite == backgroundSprite)
ClearItem();
}
public void SetIventoryUiElement(string name, int count, Sprite image)
{
itemName = name;
itemCount = count + "";
if (!isHotbarItem)
nameText.text = itemName;
countText.text = itemCount;
isEmpty = false;
SetImageSprite(image);
}
// SwapWithData will help with the implementation of the drag and drop system
// to switch between the empty and non empty items from the inventory or the hot bar
public void SwapWithData(string name, int count, Sprite image, bool isEmpty)
{
SetIventoryUiElement(name, count, image);
this.isEmpty = isEmpty; //may want to set to true
}
private void SetImageSprite(Sprite image)
{
itemImage.sprite = image;
}
private void ClearItem()
{
itemName = "";
itemCount = "";
countText.text = itemCount;
if (!isHotbarItem)
nameText.text = itemName;
ResetImage();
isEmpty = true;
ToggleHighlight(false);
}
private void ToggleHighlight(bool val)
{
outline.enabled = val;
}
private void ResetImage()
{
itemImage.sprite = backgroundSprite;
}
}