Unityゲーム用のアイテムシステムを作成しており、 C#を使用して作成しています。ItemTypeという抽象クラスがあり、特定のタイプのアイテムに関する情報(名前、重量、市場価値、IDなど)が含まれています。次に、ItemTypeクラスから継承するitemクラス、ItemSword、およびItemCoinを実行する必要があります。ItemManagerクラスもあります。このクラスはItemCoinとItemSwordをインスタンス化し、それらにIDを自動的に割り当てます。私の問題は、クラスを継承しようとするとコンストラクターでエラーが発生することです。
ItemTypeのコンストラクターは、nameという文字列という1つのパラメーターを取ります。ItemCoinのコンストラクターを実行するときは、次を使用して基本クラスを呼び出すようにします。
ItemCoin(string name): base(name){
//Stuff
}
このページに書かれているように。
エラーは、私がそれをプライベートにしたかのように、その保護レベルのために「名前」にアクセスできないことを示しています。ただし、これはパラメーターであるため、アクセス修飾子を指定していないため、これがどの ように可能かはわかりません。ItemSwordでこのエラーが発生することはありませんが、コンパイラがまだItemCoinでスタックしていることが原因である可能性があります。
「base」にパラメーターを指定しないと、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];
}
}