我正在为我的 Unity 游戏制作一个项目系统,并且我正在使用 C# 来完成它。我有一个名为 ItemType 的抽象类,它包含有关特定类型项目的信息(例如其名称、重量、市场价值、ID 等)。然后我必须从 ItemType 类继承的项目类、ItemSword 和 ItemCoin。我还有一个 ItemManager 类,它实例化 ItemCoin 和 ItemSword 并自动为我分配一个 ID。我的问题是,当我尝试继承类时,构造函数出现错误。
ItemType 的构造函数采用一个参数,一个名为 name 的字符串。当我去为 ItemCoin 做构造函数时,我确保它使用调用基类
ItemCoin(string name): base(name){
//Stuff
}
就像它在此页面上所说的那样。
错误是说“名称”由于其保护级别而无法访问,就好像我已将其设为私有一样。 不过,我不明白这是怎么可能的,因为我没有给它任何访问修饰符,因为它是一个参数。ItemSword 没有给我这个错误,但这可能是因为编译器仍然卡在 ItemCoin 上。
当我不给“base”任何参数时,它告诉我 ItemType 没有带有 0 个参数的构造函数。如果我根本不使用“base”,或者我不给它任何构造函数,也会发生同样的事情。
作为参考,这是我的完整源代码。
项目类型.cs:
using UnityEngine;
using System.Collections;
public abstract class ItemType{
public int itemID; //The id of this item
public string itemName; //The text name of this item
public int stackSize = 99; //The maximum amount of this item allowed in a stack. Use -1 for infinite
public int maxAllowedInOneContainer = -1; //The maximum amount of this item allowed in a single container. Use -1 for infinite.
public int weight = 0; //The weight of this item
public int marketValue = 0; //The standard price of this item in stores
ItemType(string name){
itemName = name;
}
}
ItemCoin.cs:
using UnityEngine;
using System.Collections;
public class ItemCoin : ItemType {
ItemCoin(string name): base(name){
stackSize = -1;
}
}
ItemSword.cs:
using UnityEngine;
using System.Collections;
public class ItemSword : ItemType{
ItemSword(string name): base(name){
maxAllowedInOneContainer = 1;
stackSize = 1;
}
}
物品管理器.cs:
using UnityEngine;
using System.Collections;
public class ItemManager {
public const int MAX_ITEMS = 3200;
private static ItemType[] itemList = new ItemType[MAX_ITEMS];
public static int numberOfItems = 0;
ItemManager(){
/*When you make a new item, add it to this huge list of item declarations, or else it won't do anything!*/
ItemSword sword = addItem(new ItemSword("Sword")); //Adds the sword item
ItemCoin coin = addItem(new ItemCoin("Coin"));
}
public ItemType addItem(ItemType item){
//Add the item to the list
itemList[numberOfItems] = item;
//Tell the item its id number
item.itemID = numberOfItems;
//Increment the total number of items by one. This will be the id of the next added item.
numberOfItems += 1;
return item;
}
public int findItemID(string name){
//Finds the item id for an item with a given name
bool found = false;
for (int i = 0; i < numberOfItems; i++){
if (itemList[i].itemName == name){
found = true;
return itemList[i].itemID;
break;
}
}
if (found == false){
throw new ItemIDNotFoundException();
}
}
public string findItemName(int id){
if (id >= itemList.Length){
throw new ItemIDNotFoundException();
}
else{
return itemList[id].name;
}
}
public ItemType GetItem(int id){
//Returns a reference(pointer) to the item type with a given id.
return itemList[id];
}
}