Search Unity

lambda expression with arrays

Discussion in 'Scripting' started by Deleted User, Sep 26, 2015.

  1. Deleted User

    Deleted User

    Guest

    hi!

    Code (CSharp):
    1. GameObject[] targets;
    2. GameObject current = targets.Min( target => Vector2.Distance(this.transform.position, target.transform.position) );
    pls help me. how can i find the closest target with lambda expression? the monodevelop said:
    "A field initializer cannot reference the non-static field, method, or property 'teszt.targets' "

    i think lambda expression would be rly usefull but it is the first time when i try it.

    sry for my terrible english.
    thx any advice
     
  2. Rostam24

    Rostam24

    Joined:
    Mar 5, 2014
    Posts:
    119
    Where have you put that code?
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Put it inside a method. You can't (mostly) call methods when you declare a variable at the class level.
     
    Deleted User likes this.
  4. Deleted User

    Deleted User

    Guest

    thx . i put it in the start function then. the new error is:
    " 'System.Array' does not contain a definition for 'Min' and no.extension method 'Min' accepting a first argument of tzpe 'System.Array' could be found.

    how can i use the lambda expression for array then? can u correct me, pls
     
  5. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    Cast the array to a list with .ToList() than do the .min expression