Search Unity

Weird Array/List behavior.

Discussion in 'Scripting' started by Cyber-Dog, Dec 15, 2019.

  1. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    Hey,

    I'm having an indexing issue with my code. I have swapped array/list to see if something was up there but not seeing any difference in behavior.

    Here I debug to get the count and the index I am trying to reach. Currently, the debug will return (2, 0)
    Code (CSharp):
    1. Debug.Log(component.GetType().GetProperties().Where(x => x.PropertyType == targetType).ToList().Count() + " - " + fieldIndex);
    Now here I will try and access the first item on the list. That's when I get an index out of range error. Though the above debug log has just shown that I'm trying to get a valid index.
    Code (CSharp):
    1. Debug.Log(component.GetType().GetFields().Where(x => x.FieldType == targetType).ToList()[fieldIndex].GetValue(component));
    So after that I'm thinking something is up with what I am trying to get. So I check if the first item in the list is null... This I get the error "InvalidOperationException: Sequence contains no elements"
    Code (CSharp):
    1. Debug.Log(component.GetType().GetFields().Where(x => x.FieldType == targetType).ToList().First() == null);
    I have jumped into the debugger and proved that there are no null objects and that the properties can be read.
    This doesnt seem to happen every time, but it does happen on certain values I am trying to test. Like this instance Transform.name fails.




    Any help would be greatly appreciated ;)
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    This is why I tend to avoid Linq. It just isn't clear enough what is going on, and honestly I cannot even tell. If this code was submitted to me for code review I would have to reject it.

    Try rewriting the line as series of steps exactly how you would explain it to a human: get this list, choose that, etc. and I am sure the problem will become evident.
     
    Madgvox and Cyber-Dog like this.
  3. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    Im dubber than a dore nail sometimes :confused:
    I worked it out, I'm making calls to two different lists when one is not meant to be used. Not very efficient -_-
     
  4. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    To anyone who cares. Its all ended in success.

    I have added functionality to the GameCreator.io asset, giving GameCreator access to scripted variables.

     
  5. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,317
    +1 for no Linq.
     
    Kurt-Dekker likes this.
  6. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    Im just a modern day sociopath haha

    I love my one liners :D