Menu
CoddyTech

Công thức chế tạo

Thuộc phần Kiến trúc trò chơi trong Unity trong hành trình Unity của Coddy. Bài học 63 trên 64.

challenge icon

Thử thách

Khó

Thêm công thức chế tạo cho CraftingBench.

  1. Thêm Ingredient có thể tuần tự hóa (công khai item, amount) và Recipe (công khai result, List<Ingredient> needs), cùng với List<Recipe> recipes công khai.
  2. Trong Start, recipeButtons[i] gọi Craft(i).
  3. public void Craft(int index): khi có đủ mọi nguyên liệu cần thiết, hãy xóa chúng, thêm một sản phẩm và ghi nhật ký Crafted Axe.
  4. Refresh chỉ cho phép nhấn nút khi có thể chế tạo công thức tương ứng.

Nhấn Chơi và chế tạo một chiếc bè. Sau đó, nhấn Kiểm tra.

Tự làm thử

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class CraftingBench : MonoBehaviour
{
    [SerializeField] private Inventory inventory;
    [SerializeField] private Button[] recipeButtons;
    [SerializeField] private Button woodButton;
    [SerializeField] private Button stoneButton;
    [SerializeField] private TMP_Text inventoryText;

    void OnEnable()
    {
        inventory.Changed += Refresh;
    }

    void OnDisable()
    {
        inventory.Changed -= Refresh;
    }

    void Start()
    {
        woodButton.onClick.AddListener(() => inventory.Add("Wood", 1));
        stoneButton.onClick.AddListener(() => inventory.Add("Stone", 1));
        // Công thức: nút công thức i chế tạo vật phẩm theo công thức i
        Refresh();
    }

    void Refresh()
    {
        // Công thức: chỉ có thể nhấn nút công thức khi có đủ nguyên liệu để chế tạo vật phẩm theo công thức đó
        inventoryText.text = "Inventory: " + inventory.Describe();
    }
}

Tất cả bài học trong Kiến trúc trò chơi trong Unity

Tự luyện tập: Playground Unity