buy in the shop and instance the object in the world

claudius_I

New member
Hello, i want to add pets to my game. i buying the pet in the shop (the pet is a item). i want to instance the pet in the world aftet buying. there is a way or a metod to do that?

Thanks

Claudio
 
This is possible but it will require some custom code.

You can set your pet prefab as an Attribute on your item.
Then when you buy the pet item you can get the attribute on the item, spawn the pet (and remove the item from the Inventory?)

To know when the item was bought you have multiple options.
But for your use case I think the easiest is to Tick the "Add Item with Callback" option on the Shop component and use the "c_InventoryGameObject_OnBuyAddItem_Shop_ItemInfo_ActionBoolSucces" event to add the item your own way.

The code below is an example. You can edit it to your liking. Just make sure to register to the event in the Start funcion of your custom script.
You'll probably want to add a check to make sure the item bought is a pet and not something else. You can do so by checking if the category match.

Code:
public void RegisterToShopBuyEvent()
{
    var myPlayerGameobject = gameObject;
    Opsive.Shared.Events.EventHandler.RegisterEvent<ShopGeneric<CurrencyCollection>, ItemInfo, Action<bool>>(
        myPlayerGameobject,
        EventNames.c_InventoryGameObject_OnBuyAddItem_Shop_ItemInfo_ActionBoolSucces,
        HandleOnShopBuy);
}
private void HandleOnShopBuy(ShopGeneric<CurrencyCollection> shop, ItemInfo itemBought, Action<bool> result)
{
    // If you want to add the item to the Inventory do this, if not Ignore
    {
        var playerInventory = m_Inventory;
        var itemCollection = shop.GetItemCollectionToAddItemTo(playerInventory, itemBought);
            
        if (itemBought.Item.IsMutable && itemBought.Item.IsUnique) {
            for (int i = 0; i < itemBought.Amount; i++) {
                itemCollection.AddItem(InventorySystemManager.CreateItem(itemBought.Item));
            }
        } else {
            itemCollection.AddItem(itemBought);
        }
    }
    
    // Here you can get your pet and instantiated.
    var petPrefab = itemBought.Item.GetAttribute<Attribute<GameObject>>("PetPrefab").GetValue();
    var instance = Instantiate(petPrefab);
    
    
    //Important don't forget to say that the buying was successful
    result?.Invoke(true);
}

I hope that helps
 
Top