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
1
Question by byviolet · May 14, 2015 at 09:55 PM · gameobjectsproximity

Preventing gameobjects from being spawned too close to each other

I just started playing around with unity but I'm having trouble figuring out how to prevent some gameobjects I want to spawn from spawning too close to each other. My code looks like this so far:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class WorldMapPoints : MonoBehaviour {
     public GameObject waypoint;
     public int waypointNumber = 50;
     public int minimumYAllowed = 10;
     public int minimumXAllowed = 10;
 
     private List <Vector3> waypointPositions = new List<Vector3>();
     int randomPositionX; 
     int randomPositionY;
 
 
     void fillList(){
         for (int i=0;i<=waypointNumber;i++){
             waypointPositions.Add(new Vector3(randomPositionX, randomPositionY,0f));
             randomPositionX =Random.Range(-300,300);
             randomPositionY =Random.Range(-300,300);
             Instantiate(waypoint, new Vector3(randomPositionX, randomPositionY,0f),Quaternion.identity);
     
 
 
         }
 
     
     }
 
 
 
 
     void Start(){
         randomPositionX =Random.Range(-300,300); 
         randomPositionY =Random.Range(-300,300);
         fillList ();
 
     }
 
 }
 

 

I'm 100% certain this code looks horrible and it definitely doesn't do what I want it to do. I can't figure out how to check if the location of the waypoint spawned is too close to any waypoint spawned previously.

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

Answer by cjdev · May 15, 2015 at 08:36 AM

You could try something like this:

     public GameObject waypoint;
     public int waypointNumber = 10;
     public float minDistance = 10f; // Each waypoint must be radius 10 apart
     private List<Vector3> waypointPositions = new List<Vector3>();
 
 
     void Start () {
         FillList();
     }
 
     void FillList()
     {
         for (int i = 0; i < waypointNumber; i++)
         {
             for (int j = 0; j < 50; j++ ) // Gets a new random position until a valid one is found, ideally runs once
             {
                 Vector3 randomPosition = new Vector3(Random.Range(-300, 300), Random.Range(-300, 300), 0);
                 bool close = false;
                 foreach (Vector3 wp in waypointPositions) // foreach loop cycles through each type (Vector3) in the list and names it (wp)
                 {
                     if (Vector3.Distance(wp, randomPosition) < minDistance) close = true;  // Compares the distance between the random point and each existing waypoint
                 }
                 if (!close) // If the new point is valid add it to the list, instantiate it, and break out of the j-indexed for loop
                 {
                     waypointPositions.Add(randomPosition);
                     Instantiate(waypoint, randomPosition, Quaternion.identity);
                     break;
                 }
             }
         }
     }


Basically it just uses Vector3.Distance to compare the new random vector with your list of existing vectors. The for loop with the j-index runs up to 50 times in case the random vector is too close and a new position needs to be calculated. For the distances you have it isn't likely to have to run more than a couple times, but it's generally better to have a finite loop rather than a while(true) loop with no breaking variable. I'm sure there are other ways to do it, that's what's great about programming, but I doubt you would get any performance gains from it.

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 byviolet · May 16, 2015 at 04:10 AM 0
Share

this is brilliant, thanks so much!

avatar image TimLoo6 · Apr 01, 2020 at 08:08 AM 0
Share

What if we have a list of spawn points rather than a field with a range?

avatar image
0

Answer by Lunar Soul · May 15, 2015 at 08:27 AM

I think the simplest way to execute this is to: Set an int named Previousx and PreviousY. So once you set the watpointPositions in void fillList(), you need to set PreviouX = randomPositionX and PreviousY = randomPostionY BEFORE you set the new random positions. Now you will need to do is make sure your new random positions are greater than or less than a certain distance of the previous x and y's.

I hope i helped.

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Proximity checker 1 Answer

Multiple Prefab in Object Pool or One Prefab With Add Component 0 Answers

Is there a way to document/leave notes on gameobjects without attaching a component to the gameobject (which adds overhead) 1 Answer

Use GetComponentsInChildren but don't access grand children 2 Answers

Make my 3D Game resolution fit all mobile devices 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