Search Unity

[Solved] Invalid cast error (foreach loop)?

Discussion in 'Scripting' started by Josiah_Ironclad, Apr 29, 2020.

  1. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    I've got this foreach loop:
    foreach (GameObject existingSlot in inventorySlots) {}


    "inventorySlots" is a Transform reference to a UI object. The way I do the inventory system is each item generates its own slot, rather than having a set number of slots which then get filled (this is purely for aesthetic purposes).

    When I pick up the first item, it just gets generated inside a slot (which also gets generated right beforehand, and is a child of inventorySlots) like it should. And when I pick up the same item again, the code in that foreach loop should do other stuff.

    Currently whenever I pick up a second item, the console spits out "InvalidCastException: Specified cast is not valid." and points to that foreach line.
     
    Last edited: Apr 29, 2020
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    It's usually helpful to just post the script along with describing your problem, but if inventorySlots is a collection of transforms, then telling it to loop through with GameObject would be your error. But then it sounds like inventorySlots is just a single transform and you're trying to loop through it's children?
     
    Josiah_Ironclad likes this.
  3. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    Yes.
     
  4. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    Oh! It was because I was trying to loop through GameObject rather than Transform. (regardless of whether the parent was a collection of, or a single transform). Thanks!
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Yep, you got it!
     
  6. kirigaya552

    kirigaya552

    Joined:
    Jan 4, 2021
    Posts:
    22
    yo thanks for helping i was doing the same thing hahahha