Search Unity

How to grab only elements that meet certain conditions in a list.

Discussion in 'Scripting' started by Sigma266, Oct 20, 2017.

  1. Sigma266

    Sigma266

    Joined:
    Mar 25, 2017
    Posts:
    99
    Hey! I made a list where I put all the enemies in my scene. In my script, I'd like to grab ONLY the enemies inside the list who have the 'effectUP' variable higher than 0. How do I do that? Thank you. If I wasn't very clear, please let me know.


    foreach(GameObject Enemy in Enemies)
    {
    if(Enemy.GetComponent<Enemy_SM>().effectUP > 0)
    {
    // Grab enemies with effectUP higher than 0. But how??
    }
    }
     
  2. mentalzoneoverride

    mentalzoneoverride

    Joined:
    Aug 1, 2017
    Posts:
    2
    Hey! If you don't want to use rigidbody,i guess you can make that enemy your own player child object, after that give him right position and rotation.
     
  3. Sigma266

    Sigma266

    Joined:
    Mar 25, 2017
    Posts:
    99
    Sorry, I didn't mean grab it as moving it from one place to another. I meant grabbing an element from the list to work on it from with the script. Kinda like the 'Enemy' GameObject from that foreach loop, except I just want the 'Enemy' GameObjects with 'effectUp' higher than 0.
     
  4. mentalzoneoverride

    mentalzoneoverride

    Joined:
    Aug 1, 2017
    Posts:
    2
    Oh, okay than. Let me explain the way i understand your question.

    Let's say you want to do something with the objects effectUP > 0 condition.
    foreach(GameObject Enemy in Enemies)
    {
    if(Enemy.GetComponent<Enemy_SM>().effectUP > 0)
    {
    //this block already got that.
    //you can do whatever you want to do with these objects.
    }
    else
    {
    //this block gives you the Enemy_SM.effectUp < 0
    }
    }
    Sorry if i understand you wrong. :)
     
    Sigma266 likes this.
  5. Sigma266

    Sigma266

    Joined:
    Mar 25, 2017
    Posts:
    99
    Thanks a lot for the response. I'm gonna try this right away.
     
  6. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    Mental is correct.
    but here is another example. with notes
    Code (CSharp):
    1. foreach(GameObject Enemy in Enemies)
    2. {
    3.     //you are checking every element in the array Enemies and calling each one Ememy
    4.     if(Enemy.GetComponent<Enemy_SM>().effectUP > 0)
    5.     {
    6.         //this is the Ememy you want, so lets kill him
    7.         Destroy(Enemy);
    8.     }
    9. }
     
    Sigma266 likes this.
  7. Sigma266

    Sigma266

    Joined:
    Mar 25, 2017
    Posts:
    99
    Okay, things are working just fine now. Thank you both.