The code below selects all items that are locked. How can I optimise it?
ShopItemData
doesn't contain a field for locked/unlocked.
_allItems
is a ShopItemData[]
_codaCommonShopItems
, _codaRareShopItems
, and _codaEpicShopItems
are CodaShopItem[]
s.
public class CodaShopItem : MonoBehaviour
{
private Button _itemButton;
private bool _inUse;
private int _itemId;
private CodaShopScreen.ItemRarity _itemRarity;
public int ItemId => _itemId;
public bool Unlocked;
public bool InUse => _inUse;
public CodaShopScreen.ItemRarity ItemRarity => _itemRarity;
}
public class ShopItemData : ScriptableObject
{
public int ItemId;
public Sprite ItemSprite;
public CodaShopScreen.ItemRarity ItemRarity;
public GameObject InGamePrefab;
public GameObject PreviewPrefab;
}
public IEnumerable<ShopItemData> GetLockedItems()
{
var lockedCommonItems = _codaCommonShopItems.Where(item => !item.Unlocked).ToArray();
var lockedRareItems = _codaRareShopItems.Where(item => !item.Unlocked).ToArray();
var lockedEpicItems = _codaEpicShopItems.Where(item => !item.Unlocked).ToArray();
var allLockedItems = new List<ShopItemData>();
var allItemDatas = GetAllItems().ToArray();
for (var i = 0; i < lockedCommonItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedCommonItems[i].ItemId && item.ItemRarity == lockedCommonItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
for (var i = 0; i < lockedRareItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedRareItems[i].ItemId && item.ItemRarity == lockedRareItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
for (var i = 0; i < lockedEpicItems.Length; i++)
{
var lockedItemData = allItemDatas.First(item => item.ItemId == lockedEpicItems[i].ItemId && item.ItemRarity == lockedEpicItems[i].ItemRarity);
allLockedItems.Add(lockedItemData);
}
return allLockedItems;
}
public IEnumerable<ShopItemData> GetAllItems()
{
return _allItems;
}
And this is how shop items are created
private void CreateCommonShopItems()
{
var commonItems = Resources.LoadAll<ShopItemData>(ShopItemDataPath).Where(item => item.ItemRarity == ItemRarity.Common);
var commonCategory = _itemCategories.First(item => item.ItemRarity == ItemRarity.Common);
commonCategory.Create(ref _codaCommonShopItems, commonItems.ToArray());
}
basically I am getting the item datas and passing them into another function which turns them into _codaCommonShopItem
and fill their properties
_codaCommonShopItem[i].Init(items[i].ItemId, items[i].ItemRarity, items[i].ItemSprite);
GetAllItems
code, and for simplicity, explain the releationship between_codaCommonShopItems
and_codaRareShopItems
and_codaEpicShopItems
(you can provide their models or any related FK between them. \$\endgroup\$FK
, a simpleJOIN
would solve your issue. \$\endgroup\$