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 /
  • Help Room /
avatar image
0
Question by ReceptiveRaptor · Mar 26, 2021 at 09:46 AM · foreach

Having trouble with Foreach Loops Unity 2020.3

I have a game where I have an object that will fall out of the sky from a random pre defined transform, there are 72 transforms that this object can choose at random

When I first made the code for it I had the gameobject choose a spawn point (yes!) but then... All gameobjects being instantiated spawned from that same point.

Here is my code:

 public class EnemySpawner : MonoBehaviour
 {
     public Transform spawnPointContainer;      // Assign parent gameobject of spawn points.
     private Transform[] spawnPoints;
     int random;
     [SerializeField] GameObject cubeEnemys;
     [SerializeField] int maxCubeAmount;
     [SerializeField] int currentCubeAmount;
 
     Rigidbody rb;
 
     void Awake()
     {
         CreateSpawnPointArray();
     }
     private void Update()
     {
         SpawnEnemyOnArray();
     }
     private void CreateSpawnPointArray()
     {
         // Initialize spawnPoints array.
         spawnPoints = new Transform[spawnPointContainer.childCount];
         // Populate array with child transforms.
         for (int i = 0; i < spawnPointContainer.childCount; i++)
         {
             spawnPoints[i] = spawnPointContainer.GetChild(i);
         }
         random = Random.Range(0, spawnPoints.Length);
         Debug.Log("There are: " + spawnPointContainer.childCount + " spawn points");
     }
     // TODO , cubes only spawn a few at a time, at random points each, instead of the current blood fountain.
     private void SpawnEnemyOnArray()
     {
         for (currentCubeAmount = 0; currentCubeAmount < maxCubeAmount; currentCubeAmount++)
         {
             if (currentCubeAmount >= maxCubeAmount)
             {
                 return;
             }
             GameObject clone = Instantiate(cubeEnemys, spawnPoints[random].transform.position, transform.rotation) as GameObject;
             Vector3 cubeVelocity = new Vector3(-1, -1, -1);
             clone.GetComponent<Rigidbody>().AddForce(cubeVelocity, ForceMode.Force);
         }
     }
 }
     
 

In case someone wants context, this is the "blood fountain" https://imgur.com/a/1DcV4wI This image was taken as soon as the gameobjects start to spawn, probably like 3 seconds after starting the scene, by the time the gameobjects start to spawn there are over 1000 of them.

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by ReceptiveRaptor · Mar 27, 2021 at 08:49 AM

 public class EnemySpawner : MonoBehaviour
 {
     public Transform spawnPointContainer;      // Assign parent gameobject of spawn points.
     private Transform[] spawnPoints;
     int random;
     [SerializeField] GameObject cubeEnemys;
     [SerializeField] int maxCubeAmount;
     [SerializeField] int currentCubeAmount;
 
     Rigidbody rb;
 
     void Awake()
     {
         CreateSpawnPointArray();
     }
     private void Update()
     {
         SpawnEnemyOnArray();
     }
     private void CreateSpawnPointArray()
     {
         // Initialize spawnPoints array.
         spawnPoints = new Transform[spawnPointContainer.childCount];
         // Populate array with child transforms.
         for (int i = 0; i < spawnPointContainer.childCount; i++)
         {
             spawnPoints[i] = spawnPointContainer.GetChild(i);
         }
 
         random = Random.Range(0, spawnPoints.Length);
         Debug.Log("There are: " + spawnPointContainer.childCount + " spawn points");
     }
     // TODO , cubes only spawn a few at a time, at random points each, instead of the current blood fountain.
     private void SpawnEnemyOnArray()
     {
         for (int i = 0; i < maxCubeAmount; currentCubeAmount++)
         {
             if (currentCubeAmount >= maxCubeAmount)
             {
                 return;
             }
 
             else
             {
                 foreach (Transform spawnPoint in spawnPoints)
                 {
                     GameObject clone = Instantiate(cubeEnemys, spawnPoints[random].transform.position, transform.rotation) as GameObject;
                     Vector3 cubeVelocity = new Vector3(-1, -1, -1);
                     clone.GetComponent<Rigidbody>().AddForce(cubeVelocity, ForceMode.Force);
                 }
             }
         }
     }
 }
 

_

So I have played around with the code a little, I think I am beginning to understand foreach loops properly, this current version of the code still has gameobjects spawn at the start of the scene but there are 430 down from the 1300+


I also don't have "blood fountain" anymore, when the code is ran the first time I don't get any more new spawns once garbage collection takes care of the ones that fly off the stage.


Oooh, I've just realized that the amount of objects spawning is actually falling in line with "Max Cube Amount" as setting Max Cube Amount to 1 in the inspector is only spawning.... God Damn it. 72 Cubes....


sigh

Comment
Add comment · 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

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

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

c# foreach does not work 0 Answers

Retrieving values from list of Scriptable Objects 1 Answer

foreach raycast hit fmod parameter -0.2 f? 0 Answers

InvalidOperationException: Collection was modified; enumeration operation may not execute. 0 Answers

Foreach and GetComponentInChildren, getting NullReferenceException 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