Newer
Older
Hierarchical-Task-Network-Unity-3D / Assets / Scripts / Example / Conditions / IsProductAvailable.cs
using System;
using UnityEngine;

public class IsProductAvailable : Condition
{
    // ================== VARIABLES ==================
    private string productName;

    // ================== CONSTRUCTOR ==================
    public IsProductAvailable(string productName) : base("Is Product Available") => this.productName = productName;

    // ================== CONDITION ==================
    public override bool IsConditionMet(HTNPlanner planner)
    {
        //Get the product section
        SectionHandler section = planner.WorldState.Get<SectionHandler>($"{productName}");

        //If the section exists
        if (section != null)
        {
            //Cast
            Customer customer = planner.Agent as Customer;

            if (customer == null) 
            {
                Debug.LogError("Cast Failed!");
                return false;
            }

            //Get's the quantity amount of the product from the customer wishlist
            int productQuantity = customer.wishList.TryGetValue(section.Product.ID, out int value) ? value : 0;

            if (productQuantity == 0)
            {
                Debug.LogError("The product quantity is 0");
                return false;
            }

            //Checks if the shelf has product, and also if the stock of the product is enough to satisfly the customer
            if (section.CurrentAmount != 0 && section.CurrentAmount >= productQuantity)
            {
                Debug.Log($"The section has {section.CurrentAmount} of {productName}");
                return true;
            }

            Debug.Log($"The section has {0} {section.Product.name} available");
            return false;
        }

        else
        {
            Debug.LogError("Section doesn't exist");
            return false;
        }
    }
}