如何在Angelscript中访问数组元素?游戏库存系统数组咨询
Hey there! Let's clear up the confusion around that string[] inventory(2); line and get your game's inventory system working like you want it to.
First, what does string[] inventory(2); actually mean?
That line creates a single-dimensional array of strings that starts with exactly 2 empty string elements. The (2) is just setting the initial size of the array—so you'd have inventory[0] and inventory[1], each holding an empty string by default.
The problem here is this isn't the right structure for your inventory: you need to store multiple items, each with their own name and description. A 2-element string array can only hold two separate strings, not pairs of data for multiple items. That's why your code runs but doesn't do what you expect!
The Right Approach: Use a Struct for Inventory Items
AngelScript lets you define custom data structures to group related info together—perfect for your items. Here's how to do it:
// Define a struct to hold each item's details struct InventoryItem { string itemName; string itemDescription; }; // Now create an array of this struct to hold your inventory InventoryItem[] inventory;
Adding Items to Your Inventory
Once you have the struct set up, you can easily add items like this:
// Create a new item and populate its fields InventoryItem ironSword; ironSword.itemName = "Iron Sword"; ironSword.itemDescription = "A reliable blade that deals moderate damage to foes."; // Add it to the inventory array inventory.push_back(ironSword); // You can also do this in one line if you prefer (cleaner!) inventory.push_back({ "Healing Potion", "Restores 50 health when consumed. Great for tough fights." });
Accessing Inventory Items
To get the name or description of an item, you use array indexing (remember, arrays start at 0!) followed by the struct field:
// Get the first item's name and description string firstItemName = inventory[0].itemName; string firstItemDesc = inventory[0].itemDescription; // Loop through all items in the inventory (great for displaying them!) for (uint i = 0; i < inventory.length; i++) { // Print or display the item details print("Item #" + (i + 1) + ": " + inventory[i].itemName); print("Description: " + inventory[i].itemDescription + "\n"); }
What If You Really Wanted to Use a 2D Array?
While structs are way more readable and maintainable, if you insisted on using arrays for pairs of data, you could use a 2D string array:
// A 2D array where each sub-array holds [name, description] string[][] inventory; // Add an item inventory.push_back({"Leather Armor", "Lightweight armor that offers basic protection."}); // Access it string armorName = inventory[0][0]; string armorDesc = inventory[0][1];
But again—stick with the struct. It'll make your code easier to debug and expand later (like adding item stats, weights, etc.).
内容的提问来源于stack exchange,提问作者captainx

