Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 Chocolade · Oct 11, 2017 at 07:56 AM · c#scripting problemscript.

How can i spawn random number of prefabs in random positions with gap of 10 inside a rectangle area ?

Not the terrain but inside a rectangle area i built with another script. Rectangle of cubes.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class RandomSpawnObjects : MonoBehaviour
 {
     public Terrain terrain;
     public GameObject[] prefabs;
     public int prefabsNumber;
     public int positionArea;
     public int gap = 3;
 
     // Use this for initialization
     void Start ()
     {
         var walls = GetComponent<Walls>();
         var spawnArea = walls.wallsSize;
 
         prefabsNumber = Random.Range(5, 30);
         positionArea = Random.Range(3, 30);
 
         for (int i = 0; i < prefabsNumber; i++)
         {
             Instantiate(prefabs[i], prefabs[i].transform.position, Quaternion.identity);
         }
     }
     
     // Update is called once per frame
     void Update ()
     {
         
     }
 }
 

walls.wallsSize give me the size for example 100 so the area will be 100*100 like 100 width and 100 height. But not sure how to get it calculate the area from walls.wallsSize

Then what i want to do is to Instantiate random number of prefabs in random positions within the walls size area and gap/space between the prefabs of 10 for example and if a prefab is randomly Instantiated near one of the walls also keep gap of 10 from the wall/s

Also making each prefab a random rotation angle is good option.

Comment
Add comment · Show 2
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 Yuvii · Oct 11, 2017 at 08:46 AM 1
Share

Hey,

Sorry but i don't really get what you mean. Can you clarify a bit more what exactly do you want ?

avatar image Chocolade Yuvii · Oct 11, 2017 at 11:32 AM 0
Share

Yes.

I have one script that create a rectangle:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Walls : $$anonymous$$onoBehaviour
 {
     public Vector3 scaleFactor;
     public float wallsSize;
     public bool scaleDown = false;
 
     private bool changepos = false;
 
     private void Update()
     {
         if (scaleDown == false)
         {
             if (transform.localScale.x != wallsSize && transform.localScale.z != wallsSize)
             {
                 transform.localScale += new Vector3(scaleFactor.x, scaleFactor.y, scaleFactor.z);
             }
         }
 
         if (scaleDown == true)
         {
             if (changepos == false)
             {
                 transform.position = new Vector3(transform.position.x + wallsSize,0, transform.position.z + wallsSize);
                 changepos = true;
             }
 
             if (transform.localScale.x != -wallsSize && transform.localScale.z != -wallsSize)
             {
                 transform.localScale -= new Vector3(scaleFactor.x, scaleFactor.y, scaleFactor.z);
             }
         }
     }
 }
 

This walls script is working fine.

Then i have the second script that with it i want to spawn objects inside the walls area:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class RandomSpawnObjects : $$anonymous$$onoBehaviour
 {
     public Terrain terrain;
     public GameObject[] prefabs;
     public int prefabsNumber;
     public int positionArea;
     public int gap = 3;
 
     // Use this for initialization
     void Start ()
     {
         var walls = GetComponent<Walls>();
         var spawnArea = walls.wallsSize;
 
         prefabsNumber = Random.Range(5, 30);
         positionArea = Random.Range(3, 30);
 
         for (int i = 0; i < prefabsNumber; i++)
         {
             Instantiate(prefabs[i], prefabs[i].transform.position, Quaternion.identity);
         }
     }
     
     // Update is called once per frame
     void Update ()
     {
         
     }
 }
 

I will give example using Paint of what i mean. The first image is just a red rectangle that the script walls:

Rectangle Walls

And this image is what i want it to do in the second script RandomSpawnObjects spawning gameobjects inside the rectangle area: Drawn them in black:

rect with objeects

rect002.jpg (28.9 kB)
rectwithobj.jpg (41.1 kB)

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Yuvii · Oct 11, 2017 at 11:56 AM

Ok, i think i get it.

So you have to spawn your assets randomly inside the rectangle. First you have to determine the minX, axX, minY and maxY of your rectangle. Then when a simple Instantiate function, you spawn them randomly inside these coordinates.

alt text

 Instantiate(*your object*, new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY)), *your quaternion*);


that way the instatiated prefabs will be in the rectangle, or at least the pivot of the prefabs. To have a random rotation, just use Quaternion.Euler(0.0, 0.0, Random.Range(0.0, 360.0) as a quaternion if of course it's the z value that you want to randomize. Saw in this topic.

And now if you want your instantiated prefabs to have a gap of 10 between each, then use an random integer and multiply it by 10

 int randomIntX = Random.Range (Mathf.RoundToInt(minX/10), Mathf.RoundToInt(maxX/10));
 int randomIntY = Random.Range (Mathf.RoundToInt(minY/10), Mathf.RoundToInt(maxY/10));
 
 Instantiate(*your object*, new Vector2(randomIntX, randomIntY) * 10, *your quaternion*);


Tell me if it works that way :)


dazdzad.png (17.9 kB)
Comment
Add comment · Show 2 · 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 Chocolade · Oct 11, 2017 at 12:40 PM 0
Share

Not sure how to find the $$anonymous$$X, axX, $$anonymous$$Y and maxY of the rectangle. Any leading clue please ?

avatar image NoBrainer-David · Oct 11, 2017 at 01:28 PM 0
Share

And now if you want your instantiated prefabs to have a gap of 10 between each, then use an random integer and multiply it by 10

Note, that this only guarantees a gap of 10 between the center points of the objects. This is probably not what the OP wants. He probably wants a gap of 10 between the volumes (i.e. the colliders) of the objects.

avatar image
1

Answer by NoBrainer-David · Oct 11, 2017 at 03:00 PM

There are two parts to your question. I will try to answer them after another.

1. How do you ensure that the obstacle spawning is done after the wall generation?

This can be done by writing a coordinating MonoBehavior, SpawnSequence. SpawnSequence will hold a reference to your wall generator and your obstacle generator. The generators will no longer use the Start method to start doing their stuff. Instead, SpawnSequence will call the spawning functions in the order you choose.

A bare-bones example would look something like this:

 public class SpawnSequence : MonoBehaviour
 {
     public EnvironmentSpawner environmentSpawner;
     public ObstacleSpawner obstacleSpawner;
 
     public void Start()
     {
         environmentSpawner.SpawnEnvironment();
 
         obstacleSpawner.SpawnObstacles(environmentSpawner.GetEnvironmentBounds());
     }
 }


 public class EnvironmentSpawner : MonoBehaviour
 {
     public Vector3 spawnAreaSize;
 
     public void SpawnEnvironment()
     {
         // Spawn the walls here
     }
 
     public Bounds GetEnvironmentBounds()
     {
         return new Bounds(transform.position, spawnAreaSize);
     }
 }

 public class ObstacleSpawner : MonoBehaviour
 {
 
     public void SpawnObstacles(Bounds bounds)
     {
 
     }
 }   

2. How do you ensure that the obstacles are at least 10m apart?

Spawning Visualization

In your comments above you posted a function isSpaceClear that casts a sphere at the candidate point and checks for overlaps. This ensures that the distance between the candidate point and any collider is not smaller than the desired gap (red line in the diagram). However, you want to calculate the closest distance between two colliders (the purple line in the diagram above). This is not impossible, but might require some thought, as there are many types of colliders and each combination might need a unique way of calculating the distance between them. This can be mitigated by making some assumptions. For example, you could assume that your obstacles may only contain one Collider and that it may only be of one type (for example BoxCollider would probably work fine as a start).

Then, spawning the obstacles one after another and checking the distance condition after each is the right way to do it. However, you have to keep in mind that it might not be possible to spawn the desired amount of obstacles in a given space. By specifying a spawn area of size 0, for example, no obstacle will be able to be spawned. This will result in an infinite loop, freezing Unity.

I would suggest keeping track of the number of times you retried a spawn iteration and just giving up entirely after maybe a thousand retries or so.


spawningvisualization.png (16.9 kB)
Comment
Add comment · Show 2 · 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 Dragate · Oct 11, 2017 at 03:45 PM 1
Share

You're right. It came to my $$anonymous$$d about the distance after spawning the object after I left and overlooked the infinite loop case. $$anonymous$$y bad, it's a faulty answer!

avatar image NoBrainer-David Dragate · Oct 12, 2017 at 07:33 AM 0
Share

Hey, don't be too hard on yourself. I thought the overall approach was well thought out! Adding the objects one by one, putting the condition checking into its own method and using Physics.SphereCast, those were very good choices, in my opinion! It just needed a little tuning. Did you delete it?

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

424 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image 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

Enabling & Disabling Script via On Click 1 Answer

How can I check if a object in the hierarchy have been destroyed using EditorWindow type script ? 1 Answer

Can someone please help me find out what wrong with my code. 0 Answers

Reverse memcpy for NativeArray? 0 Answers

The laser problems 0 Answers


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