• 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
Question by rashiddev · Jul 30, 2018 at 11:01 PM · spawnspawningspawning problemsspawnerspawning-enemies

How to spawn enemies at different locations and avoid overlapping each other

Hi everyone,

T$$anonymous$$s is my first question here.

Heres my problem: I want to spawn enemies at different location (I have already managed to do that) but I want each enemy to spawn in a different location where it doesn't overlap other enemies.

My code:

 public class SpawnManager : MonoBehaviour {
 
     [SerializeField] GameObject[] asteroidPrefab;
 
     private float currentSpawn;
 
     void Start () {
        
     }
     
     // Update is called once per frame
     void Update () {
        
     }
 
     public void spawnAsteroids()
     {
       
         StartCoroutine(spawner());
         
     }
 
     IEnumerator spawner()
     {
         w$$anonymous$$le (true)
         {
             Instantiate(asteroidPrefab[Random.Range(0, 3)], new Vector3(Random.Range(-7.0f, 7.0f), 7, 0), Quaternion.identity);
             yield return new WaitForSeconds(5.0f);
         }   
     }
 }

T$$anonymous$$s happens when the Random.range spawns enemies at close locations.

Is there a way that to avoid that?

Thank you.

Comment

People who like this

0 Show 1
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 SamohtVII · Jul 31, 2018 at 03:33 AM 0
Share

Maybe set a collision detection and just say if colliding with another enemy destroy(this).

2 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Code1345 · Jul 30, 2018 at 11:05 PM

Just to clarify, you just don't want two enemies spawning at the same location right? Just making sure I understand your problem.

Comment

People who like this

0 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 rashiddev · Jul 30, 2018 at 11:14 PM 0
Share

Yup Exactly!

avatar image Code1345 rashiddev · Jul 30, 2018 at 11:19 PM 0
Share

Great- My first idea would be to have a bool in place whenever your enemy spawns at a location- if it was true, no more enemies would spawn there until it was false. But to do that you would need a system to check if an enemy has spawned in there. Do the locations your enemies are spawning in at have colliders? Or are they just coordinates?

avatar image rashiddev Code1345 · Jul 30, 2018 at 11:25 PM 0
Share

Thank you for your reply yes they have colliders!

Show more comments
avatar image

Answer by Harinezumi · Jul 31, 2018 at 07:58 AM

I've recently did an implementation of t$$anonymous$$s. Basically whenever I instantiate my prefab, I store it in a list of existing instances ( instances.Add(newInstance);), and when it "dies", I remove it from t$$anonymous$$s list. Then before instantiating I first generate the position, and go through the list of instances to check if the position overlaps. If it does, I generate a new position. However, after a set number of tries I just stop, because if there is no space, I don't want to get into an infinite loop.
In code:

 public class SpawnManager : MonoBehaviour {
 
     [SerializeField] private AsteroidLogic[] asteroidPrefabs = null; // assign asteroid prefabs to it from Editor
     [SerializeField] private maxPositionRetries = 5;
 
     private List<AsteroidLogic> existingAsteroids = new List<AsteroidLogic>();
     public void AddAsteroid (AsteroidLogic value) { existingAsteroids.Add(value); }
     public void RemoveAsteroidLogic (AsteroidLogic value) { existingAsteroids.Remove(value); }
 
     public void Spawn () {
         AsteroidLogic asteroidPrefab = asteroidPrefabs[Random.Range(0, asteoidPrefabs.Length)];
         // probably check if the selected asteroidPrefab is not null!
 
          int numTries = 0;
          do {
              // generate a position, and check if it valid
              Vector3 position = new Vector3(Random.Range(-7.0f, 7.0f), 7, 0);
              if (IsValidPosition(position, asteroidPrefab.transform.localScale)) { // assign the second parameter (size) correctly, for example from the extents of the asteroid's collider, or get it from the AsteroidLogic
                  AsteroidLogic newAsteroid = Instantiate(asteroidPrefab, position, Quaternion.identity);
                  newAsteroid.SetSpawnManager(t$$anonymous$$s);
                  break; // new asteroid generated, break out of loop
              }
          } w$$anonymous$$le (numTries++ < maxPositionRetries);
     }
 
     private bool IsValidPosition (Vector3 positionToCheck, Vector3 objectSize) {
         for (int i = 0; i < existingAsteroids.Length; ++i) {
             AsteroidLogic asteroid = existingAsteroids[i];
             Vector3 asteroidPosition = asteroid.transform.position;
             Vector3 asteroidSize = asteroid.transform.localScale; // assign t$$anonymous$$s correctly, e.g. from the collider's extents
 
              Vector3 positionDifference = positionToCheck - asteroidPosition;
              Vector3 sizeSum = objectSize + asteroidSize;
              // if the positions are less than the sum of the extents, they overlap; also check for z coordinate if you change that
              if (Mathf.Abs(positionDifference.x) < sizeSum.x && Mathf.Abs(positionDifference.y) < sizeSum.y) { return false; } 
         }
         return true;
     }
 
 }
 
 public class AsteroidLogic : MonoBehaviour {
 
     private SpawnManager spawnManager;
 
     // automatically register itself when the manager is set
     public void SetSpawnManager (SpawnManager value) {
         spawnManager = value;
         spawnManager.AddAsteroid(t$$anonymous$$s);
     }
 
     // automatically unregister itself when it gets destroyed
     private void OnDestroy () {
         if (spawnManager != null) { spawnManager.RemoveAsteroid(t$$anonymous$$s); }
     }
 
 }
Comment

People who like this

0 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 rashiddev · Jul 31, 2018 at 08:55 PM 0
Share

Does this code work for you?

avatar image Harinezumi rashiddev · Jul 31, 2018 at 09:13 PM 0
Share

Well, it is not copy-paste from Visual Studio, so there can be syntax errors, but the general logic is sound. Of course, the AsteroidLogic class should be in its own source file called AsteroidLogic.cs, and the asteroid prefabs need this component on them.

What doesn't work? It doesn't compile, or causes Unity to hang (infinite loop), or...?

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

93 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

Related Questions

How to spawn all humans at once and activate then with time? 1 Answer

SPAWNING ENEMIES and controlling the amount/interval 1 Answer

Spawning help 1 Answer

How to prevent multiple spawns from a single spawn point? 1 Answer

How to increase the spawn rate of an object over time? 2 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