Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 MrFlyingTurtles · Mar 15, 2019 at 08:54 PM · arraylistforeachindex

How do I find a local variables index in a foreach loop?

Hey all. I'm trying to set up a script that instantiates multiple objects of the same type in different stored positions with different stored rotations. I feel like I'm really close, but I'm having trouble with this one issue. I find all the objects of class Barrel in the scene, then store that in an array. I then go through a foreach loop, adding every position of that barrel to a list of barrelPositions. After that, I set up another foreach loop function, this time instantiating a barrelPrefab at every barrelPosition on the list, but since different barrels have unique positions, I'm trying to find the index of the local variable barrel and then use that index in the barrelPositions list for use in Instantiation.

Any help? Here's the relevant snippets of my code.

  Barrel[] barrels;
     Target[] targets;
     Vector3 barrelStartPos;
     Vector3 targetStartPos;
     Quaternion barrelStartRotation;
     Quaternion targetStartRotation;
 
     List<Vector3> barrelPositions = new List<Vector3>();
     List<Quaternion> barrelRotations = new List<Quaternion>();
     List<Vector3> targetPositions = new List<Vector3>();
     List<Quaternion> targetRotations = new List<Quaternion>();
 
 void Start {
 //find all barrels, then save their positions to the barrelPositions list
         barrels = FindObjectsOfType<Barrel>();
         foreach (Barrel barrel in barrels)
         {
             barrelStartPos = barrel.transform.position;
             barrelPositions.Add(barrelStartPos);
         }
         //find all barrels, then save their rotations in the same order as barrelPositions
         foreach (Barrel barrel in barrels)
         {
             barrelStartRotation = barrel.transform.rotation;
             barrelRotations.Add(barrelStartRotation);
         }
 
 }
 
 public void RespawnObjects()
     {
         //instantiate every barrel with the same rotation and positions as those with the same index in their respective lists
         foreach (Barrel barrel in barrels)
         {
             //int barrelIndex = barrels.index //here's the annoying part
             Instantiate(barrelPrefab, barrelPositions.barrelIndex, barrelRotations.barrelIndex);
         }`
 
Comment
Add comment · Show 6
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 xxmariofer · Mar 15, 2019 at 09:24 PM 0
Share

use a foor loop

 for(int i = 0; i < barrels.length; i++) { Instantiate(barrelPrefab, barrelPositions[i], barrelRotations[i]); }

tell me if this worked :)

avatar image MrFlyingTurtles xxmariofer · Mar 15, 2019 at 09:41 PM 0
Share

Doesn't seem to, no. Nothing is respawning.

avatar image xxmariofer MrFlyingTurtles · Mar 15, 2019 at 09:49 PM 0
Share

debug.log barrels.length and check how many objects should spawn

Show more comments
avatar image Ymrasu · Mar 15, 2019 at 09:29 PM 0
Share

int barrelIndex = barrels.IndexOf(barrel)

Though is there a reason you do not want to use a for loop?

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Taylor-Libonati · Mar 15, 2019 at 09:54 PM

If you need to keep track of an index the easiest way is to just make an int and add 1 each time you loop in the function. Like this:

 //Create a Variable
 int i=0; 
 //Loop through barrels
 foreach (Barrel barrel in barrels)
          {
              Instantiate(barrelPrefab, barrelPositions[i], barrelRotations[i]);
              //Add 1 to index
              i++
          }

Also it looks like you are never calling the spawn barrels function so that code will never actually run. Side note: You don't need two for each loops in your Start function. just move the rotation code right below the position code.

Comment
Add comment · Show 6 · 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 MrFlyingTurtles · Mar 15, 2019 at 10:09 PM 0
Share

I do call the function in another script, so the functions do run. The barrels will respawn, but they will often have duplicates with the same transform if they were not destroyed previously. How would you go about removing the old objects, or only spawning them if they were destroyed?

avatar image Taylor-Libonati MrFlyingTurtles · Mar 15, 2019 at 10:15 PM 0
Share

If you want to delete all the barrels after you save their positions you just use the Destroy function in Start. You can put it in the loop you already have or make a new one if you need too.

Destroy(barrels[i].gameObject);

avatar image Ymrasu MrFlyingTurtles · Mar 15, 2019 at 10:19 PM 1
Share

Perhaps ins$$anonymous$$d of destroying them you can deactivate them ins$$anonymous$$d; then ins$$anonymous$$d of Instantiating when respawning, you check if it is not active; then reactivate and reset the position and rotation.

avatar image MrFlyingTurtles Ymrasu · Mar 15, 2019 at 11:20 PM 0
Share

Honestly, I just went with this in the end. I was told it wasn't "Good practice" to do this sort of thing, but it seems like it's just so much lighter in both performance and stress. Thanks.

avatar image sylvainlugezec · May 20, 2021 at 02:43 PM -1
Share

Thanks you ! It's very useful and simple. But if we want to begin to the index 0 from the loop, the variable "i" need to be "-1" and not "0" !

avatar image Bunny83 sylvainlugezec · May 20, 2021 at 03:34 PM 1
Share

Sorry but that doesn't make much sense. Have you actually had a closer look at the code that Taylor posted? He uses "i" inside the loop and at the very end when the loop is done he increments i. Since i starts at "0" it means that i will be 0 during the first iteration. You do not increment "i" at the beginning of the loop.

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

124 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 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 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 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 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 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

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

List gives "Array index is out of range" for no reason 2 Answers

A node in a childnode? 1 Answer

Access Components forech GameObject in List 0 Answers

foreach a array inside a generic list 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