前提
配列の中身がnullだったら、Array.IndexOfメソッドを使ってその位置を取得する...というのを書いていました。
配列の型がstringだったりgameobjectだったりする場合はちゃんと機能するのですが、自作のクラスの型の場合エラーが発生してうまく機能しないです。
どうやらクラス型配列には、初期値として何か別の物が代入されてるっぽいです。
発生している問題・エラーメッセージ
error CS0019: Operator '!=' cannot be applied to operands of type 'InventoryManagement.ItemInInventory' and '<null>'
該当のソースコード
c#
1 2public ItemInInventory[] skill_inventory = new ItemInInventory[6]; 3public ItemInInventory[] item_inventory = new ItemInInventory[16]; 4 5//省略 6 7public struct ItemInInventory 8 { 9 public string id; 10 public string type; 11 public int cooldown; 12 public int ability_haste; 13 public int arm_power; 14 public int absolute_dig; 15 public float ratio_dig; 16 public int money_invested; 17 public bool availability; 18 19 public ItemInInventory(string id,string type, int cooldown, int ability_haste, int arm_power, int absolute_dig, float ratio_dig, int money_invested, bool availability) 20 { 21 this.id = id; 22 this.type = type; 23 this.cooldown = cooldown; 24 this.ability_haste = ability_haste; 25 this.arm_power = arm_power; 26 this.absolute_dig = absolute_dig; 27 this.ratio_dig = ratio_dig; 28 this.money_invested = money_invested; 29 this.availability = availability; 30 } 31 } 32 33//省略 34 35 public void AddNewItems(string newID) 36 { 37 ItemInInventory[] array; 38 if(SearchItemFromID(newID).type.ToString() == "Skill") array = skill_inventory; 39 else array = item_inventory; 40 41 /*int index = Array.IndexOf(array, null); 42 if (index > -1) 43 { 44 if(SearchItemFromID(newID).type.ToString() == "Skill"){skill_inventory[index] = ConvertIDintoStructedItem(newID);} 45 else{item_inventory[index] = ConvertIDintoStructedItem(newID);} 46 47 }*/ //配列の中身全てがnullの時でも何故かindexが -1を返すのでデバッグのために一旦コメントで無効にしました 48 49 for(int i = 0; i<array.Length; i++) 50 { 51 if(array[i] != null) // <-ここで今エラーを吐かれています 52 { 53 if(SearchItemFromID(newID).type.ToString() == "Skill"){skill_inventory[i] = ConvertIDintoStructedItem(newID);} 54 else{item_inventory[i] = ConvertIDintoStructedItem(newID);} 55 break; 56 } 57 } 58 }
試したこと
Q) そもそもItemInInventory配列が使えないのでは?
A) 使えます。値を代入して、それを呼び出すことは問題なく出来ました。
Q) もしかしたら既に別の値が入っているとか?
A) 全てのパラメーターがnullで設定されているobjectが入っていました。これを選別する方法が今度はわかりません、、
Q) 全部のパラメーターがnullでできてるobject作って、それとの比較じゃダメなの?
A) 無理でした。パラメーターにnullを入れようとすると "error CS1503: Argument 3: cannot convert from '<null>' to 'int'" ってキレられます。じゃあ初期値で入ってる君は何者だ...
回答1件