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 Stealthygolem · Oct 28, 2014 at 06:27 PM · c#2dinstantiaterandomaddforce

Random instantiate at same frame with each instantiate having unique random direction

Hello! This question should be rather short (and sweet!). I have an enemy type in my game dropping a random set of coins Range(1,10). Problem is, they all go the same way for my "coin.rigidbody2D.AddRelativeForce(randomDirection);". I thought it would go through the for-loop differently each time. How do i go about making it so?

 private int numberOfCoins;

 void Start() {
 numberOfCoins = Random.Range(1,10);
 }


 void LateUpdate() {
 [...]
 Vector2 randomDirection = new Vector2(Random.Range(-800f, 800f), Random.Range(-800f, 800f));
 
                 GameObject coin;
 
                 for (int i = 0; i < numberOfCoins; i++) {
                 coin = (Instantiate(coinPrefab, enemy.transform.position, enemy.transform.rotation)) as GameObject;
                 coin.rigidbody2D.AddRelativeForce(randomDirection);
                 }


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
3
Best Answer

Answer by Itaros · Oct 28, 2014 at 06:30 PM

Move

 Vector2 randomDirection = new Vector2(Random.Range(-800f, 800f), Random.Range(-800f, 800f));

inside for loop

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 Itaros · Oct 28, 2014 at 06:32 PM 2
Share

Additional I might recommend you to optimize your random routine:

Vector2 randomDirection = Random.insideUnitCircle * 800F;

avatar image Nidre · Oct 28, 2014 at 06:37 PM 1
Share

It would be also better if you would leave the definition out of the loop.

 Vector2 randomDirection;
 GameObject coin;
 for (int i = 0; i < numberOfCoins; i++) 
 {
     randomDirection = Random.insideUnitCircle * 800F; 
     coin = (Instantiate(coinPrefab, enemy.transform.position, enemy.transform.rotation)) as GameObject;
     coin.rigidbody2D.AddRelativeForce(randomDirection);
 }

or

 Vector2 randomDirection;
 GameObject coin;
 for (int i = 0; i < numberOfCoins; i++) 
 {
     randomDirection = randomDirection = new Vector2(Random.Range(-800f, 800f), Random.Range(-800f, 800f));
     coin = (Instantiate(coinPrefab, enemy.transform.position, enemy.transform.rotation)) as GameObject;
     coin.rigidbody2D.AddRelativeForce(randomDirection);
 }
avatar image Itaros · Oct 28, 2014 at 06:40 PM 1
Share

@Nidre why leaving definition out of loop is better? It creates scope gap, isn't it?

http://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop

avatar image Hoeloe · Oct 28, 2014 at 06:40 PM 1
Share

Just to clarify what the problem is, in case you hadn't worked it out, is that you're generating a random vector, and then looping over things "numberOfCoin" times, and using that random vector for each one.

Consider the case where you have 3 coins. Your code first generates a random direction, for example, the vector (210, 14).

Now, you start a loop from 0 to 2.

  1. You make a new coin and add a force equal to the vector generated earlier, (210,14)

  2. You make a new coin, but since the direction vector hasn't changed, you add the same force again, (210,14)

  3. You make a third coin, and again, the direction vector hasn't changed, so you add the same force a third time, (210,14).

Now all of your coins are spawned, moving in the same direction.

What you want to happen is to generate a new vector each time you go round the loop. Remember, when you write:

 for(...)
 {
 //some code
 }

The loop only goes over the code inside the loop itself, and doesn't touch anything else. Also remember that when you assign something to a value, say:

 int x = 4+6;


It stores the result of this calculation, not the calculation itself, meaning that changing variables in the arithmetic do not propagate:

 int a = 4; //a is 4
 int b = a + 4;//b is 8
 a = 1;//b is still 8

With all that said, the last thing to do is exactly what Itaros said: move the generation of the random vector into the start of the loop (and preferably with the optimisation, too). This will cause the program to generate a new variable on each run around the loop, and not just one beforehand.

avatar image Nidre · Oct 28, 2014 at 06:45 PM 1
Share

@Itaros

Well, that is something new for me. I would expect declaring it each pass of loop would create a bigger overhead.

But after reading that topic you've mentioned it actually makes more sense to put them inside the loop.

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

27 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

Related Questions

instantiating vertically 2 Answers

Instantiate ignores position 2 Answers

How to randomly spawn three non repeating gameobjects from an array? 2 Answers

Instatiating a prefab in a random position 0 Answers

Unity2D Instantiated Prefab Won't Appear in Scene 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