Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by luniac · Nov 27, 2013 at 10:47 PM · listforeach

How to use List.ForEach Method?

documentation

I'm very confused as to how to use this method. I have this code:

 var listTurrets = new List.<GameObject>();

I want to write a simple function that finds the closest gameObject in the list to the gameobject passed in as a parameter.

i know i can do this:

 var indexToReturn;
 var tempDistance;
 for(i=0; i < listTurrets.Count;i++)
 {
 calculate distance, compare with previous,replace index if smaller distance.
 }

This is easy cause i know "i" represents each object in the list as the loop iterates through it.

But for the inbuilt method listTurrets.ForEach() i dont see how to access the object in the list as the method iterates through them. I've been searching and searching and cant find a straight explanation anywhere...

Any assistance to put this confusion to rest is much appreciated :)

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Vereos · Nov 27, 2013 at 10:53 PM

I guess you meant something like this:

 for (var gameObj : GameObject in listTurrets) {
     //your actions for each gameObj
 }
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image luniac · Nov 27, 2013 at 11:55 PM 0
Share

what bout using the ForEach function

avatar image Hoeloe · Dec 01, 2013 at 01:15 PM 0
Share

Why are you insisting on this? That code will do exactly what you need it to. You can't use the ForEach function anyway because it requires language elements only available in C# (that being lambda functions), and from your code, you're using UnityScript.

avatar image Bunny83 · Dec 03, 2013 at 10:44 AM 5
Share

@Hoeloe: Actually UnityScript also supports anonymous functions. In C# you don't have to use lambdas. Lambdas are just a way to create inplace closure-delegates.

You can do something like this in UnityScript:

     var listTurrets = new List.<GameObject>();
     // [...]
     listTurrets.ForEach(function(obj:GameObject){print(obj.name);});

ForEach simply calls a function "for each" element in the list. It doesn't have to be an anonymous function. You can use any function with the right signature:

 function doSomethingWithGO(obj : GameObject)
 {
     print("GO name is: " + obj.name);
 }
 
 listTurrets.ForEach(doSomethingWithGO);

In C# it works the same (with a slightly different syntax of course).

avatar image luniac · Dec 03, 2013 at 11:04 AM 0
Share

very interesting.

avatar image Hoeloe · Dec 03, 2013 at 11:09 AM 0
Share

You're right, I apologise. Still, my point remains the same that it's fundamentally no different from a foreach loop.

Show more comments
avatar image
0

Answer by AronChan · Nov 27, 2013 at 11:05 PM

This is how i approached something similiar:

 // Target the first tower in the array of targets available to the tower
     currentTarget = towerTargets[0];
 
         // Calculate the distance from the tower to the target
         float distanceToLastTarget = Vector3.Distance(this.gameObject.transform.position, currentTarget.transform.position);
 
             // Find the closest enemy of the available targets and set it as the current target of the tower
             for (int i = 1; i < towerTargets.Count; i++)
             {
                 if ((Vector3.Distance(this.gameObject.transform.position, towerTargets[i].transform.position)) < distanceToLastTarget)
                 {
                     currentTarget = towerTargets[i];
                 }
             }

It basicly sets the first "enemy" in the target list as the towers current target and then checks if any enemies are closer one by one. If there is an enemy that is closer that enemy replaces the current target. That way you will always come out of the for loop with the target that is closest to the tower.

Comment
Add comment · Show 27 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image luniac · Nov 27, 2013 at 11:55 PM 0
Share

lol yes that works, i was just looking for a solution using the ForEach function

avatar image AronChan · Nov 28, 2013 at 01:28 AM 0
Share

i dont remember why i decided to go with the For loop (except they are faster than foreach) but there was some reasoning behind it.

if you insist on using the foreach i think it would go something like this:

         foreach (GameObject target in towerTargets)
         {
             if ((Vector3.Distance(this.gameObject.transform.position, target.transform.position)) < distanceToLastTarget)
             {
                 currentTarget = target;
             }
         }
avatar image luniac · Nov 28, 2013 at 01:50 AM 0
Share

xcept that doesnt work with a the list. it has its own method --> list.foreach()

avatar image Hoeloe · Dec 01, 2013 at 01:14 PM 0
Share

It doesn't work because foreach isn't valid in Javascript. The foreach loop in UnityScript is just written like this:

 for (var target:GameObject in towerTargets)
avatar image Hoeloe · Dec 01, 2013 at 05:12 PM 2
Share

No, because it's a C# method, not a UnityScript method, as I've already stated in a different comment. In C# you'd use it like this:

 towerTargets.ForEach((t) => { //actions here });

Which is pretty much identical to use a foreach loop - except that the variable here is called "t" rather than "target". However, I don't believe UnityScript supports lambda functions (that's a function written like this: (args) => body.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

A node in a childnode? 1 Answer

For loop does not loop C# 2 Answers

How do I compare the position of my player to each elements position of an array of GameObjects? 0 Answers

Is there a way to organize tracking of collisions? 0 Answers

null reference exception when I already checked if this was null 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges