[ad_1]
You can use events to make your scripts “communicate” independently.
First you need the gameevents. Make sure you have the script on a gameobject in your scene:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameEvents : MonoBehaviour
{
public static GameEvents gameEvents;
private void Awake()
{
gameEvents = this;
}
public event Action<Item> onItemPurchase;
public void ItemPurchaseMade(Item item)
{
if(onItemPurchase != null)
{
onItemPurchase(item);
}
}
}
Then include the trigger in your buy method:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ShopManager : MonoBehaviour
{
public int[,] shopItems = new int[9, 9];
public float coins;
public Text CoinsTXT;
void Start()
{
CoinsTXT.text = "" + coins.ToString();
//ID's
shopItems[1, 1] = 1;
shopItems[1, 2] = 2;
shopItems[1, 3] = 3;
shopItems[1, 4] = 4;
shopItems[1, 5] = 5;
shopItems[1, 6] = 6;
shopItems[1, 7] = 7;
shopItems[1, 8] = 8;
//Price
shopItems[2, 1] = 10;
shopItems[2, 2] = 20;
shopItems[2, 3] = 30;
shopItems[2, 4] = 40;
shopItems[2, 5] = 50;
shopItems[2, 6] = 65;
shopItems[2, 7] = 110;
shopItems[2, 8] = 150;
}
public void Buy()
{
GameObject ButtonRef = GameObject.FindGameObjectWithTag("Event").GetComponent<EventSystem>().currentSelectedGameObject;
if (coins >= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID])
{
coins -= shopItems[2, ButtonRef.GetComponent<ButtonInfo>().ItemID];
CoinsTXT.text = "Coins:" + coins.ToString();
Item yourItem = Item() //get your Item from ID
GameEvents.gameEvents.ItemPurchaseMade(yourItem);
}
}
}
Then listen to the event from your inventory class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory {
private List<Item> itemList;
public Inventory()
{
GameEvents.gameEvents.onItemPurchase += AddItem;
itemList = new List<Item>();
Debug.Log("Inventory");
}
public void AddItem(Item item)
{
itemList.Add(item);
}
}
It is unclear where you get the item by their ids from. That is why I left that part out. As an alternative, you could pass the itemId though the events and get the item in the inventory class.
10
[ad_2]
solved Make inventory that receives purchased items from the shop system