Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Trying to search a string variable within a List

Discussion in 'Scripting' started by byteblorg, Dec 19, 2018.

  1. byteblorg

    byteblorg

    Joined:
    Dec 13, 2016
    Posts:
    10
    Hi Everyone

    Wondering if I could get some help: Got a List that I'm reading from a textAsset, trying to search if a string variable exists inside.

    this works:

    using System.Linq;
    var results = unA.FindIndex (x => x.Contains ("diesel"));
    Debug.Log (results);

    Debug gives me the element index from the List, i.e: 324.

    HOWEVER, i need to instead do this due to the game's requirements:

    using System.Linq;
    string itemName = "diesel";
    var results = unA.FindIndex (x => x.Contains ("itemName"));
    Debug.Log (results);

    this outputs: -1 (ie can't find the index in List)instead of 324.

    Any ideas?

    Thanks!
     
    Last edited: Dec 19, 2018
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    You're using "itemName" and it searches the "itemName". Try specifying itemName as a field - without quotes.
     
  3. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    Hi, you're confusing a text value with a string variable.

    What you're doing is searching for the text "itemName":
    Code (CSharp):
    1. x => x.Contains ("itemName")
    But you want to search with whatever the value of the variable itemName is (no quotes):
    Code (CSharp):
    1. x => x.Contains (itemName)