我正在为我的Unity游戏制作道具系统,并使用C#来实现。我有一个名为ItemType的抽象类,其中包含有关特定类型物品的信息(例如其名称,重量,市场价值,ID等)。然后,我必须拥有从ItemType类继承的项目类ItemSword和ItemCoin。我还有一个ItemManager类,该类实例化ItemCoin和ItemSword并自动为它们分配一个ID。我的问题是,当我尝试继承类时,构造器出现错误。
ItemType的构造函数采用一个参数,即一个名为name的字符串。当我去做ItemCoin的构造函数时,我确保它使用
ItemCoin(string name): base(name){
//Stuff
}
就像在this page上说的那样。
错误是因为“名称”由于其保护级别而无法访问,就像我将其设为私有一样。但是,我不知道这是怎么可能的,因为我没有给它任何访问修饰符,因为它是一个参数。 ItemSword没有给我这个错误,但这很可能是因为编译器仍然停留在ItemCoin上。
当我不给“基本”任何参数时,它告诉我ItemType没有带有0参数的构造函数。如果我根本不使用“ base”,或者如果我不给它任何构造函数,则会发生相同的事情。
供参考,这是我的完整源代码。
ItemType.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;
}
}
ItemManager.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];
}
}
最佳答案
在类中,private
是默认的可访问性级别,因此,如果不指定它,则您的构造函数是私有的。