• 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
Question by LoserMangaka · May 01, 2019 at 05:50 AM · instantiatearray2d gamespawnspawning problems

Can I spawn with an array in order?

Hello,

I'm currently making a 2d endless runner game. For my endless background, i'm doing a spawner using an array, that way I could add more objects in the future and it's easier for me to manage.

I'm currently having 2 problems with this method.


1st is the script I got from tutorials, spawns the objects in my array "Randomly" however I want my objects to be spawned in order of the array. So that i could lessen the chances of the same object spawning twice next to each other.

here's the script that I used

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Spawner : MonoBehaviour
 {
 
     public GameObject[] obstaclePatterns;
 
     private float timeBtwSpawn;
     public float startTimeBtwSpawn;
     public float decreaseTime;
     public float minTime = 0.65f;
 
     private void Update()
     {
         if (timeBtwSpawn <= 0)
         {
             int rand = Random.Range(0, obstaclePatterns.Length);
             Instantiate(obstaclePatterns[rand], transform.position, Quaternion.identity);
             timeBtwSpawn = startTimeBtwSpawn;
             if (startTimeBtwSpawn > minTime)
             {
                 startTimeBtwSpawn -= decreaseTime;
             }
             
         }
         else
         {
             timeBtwSpawn -= Time.deltaTime;
         }
     }
 
 
 
 
 }
 

and it looks like this alt text


2nd Problem is that I want these objects to overlap each other. I tried sorting the layers but since it spawns randomly, it looks messed up even more. Also since this would be a repeating pattern, I was hoping for a solution that the last object spawned is always on top to create a connecting effect.

alt text

Sorry if these problems may seems too much to ask. I've spent days researching and trying to find a solution. But since this is my first game project and my first time using unity, it's been hard finding for answers.

Hopefully someone helps me out with this. It'll be much appreciated :)

Comment

People who like this

0 Show 0
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
Best Answer

Answer by Hellium · May 01, 2019 at 08:39 AM

  private List<Renderer> instances = new List<Renderer>(16);

  public int maxObstaclesCount = 10 ;
  private int lastInstantiatedObjectIndex = -1;
  private void Update()
  {
      if (timeBtwSpawn <= 0)
      {
          SpawnNextObstacle();
          timeBtwSpawn = startTimeBtwSpawn;
          if (startTimeBtwSpawn > minTime)
          {
              startTimeBtwSpawn -= decreaseTime;
          }
          
      }
      else
      {
          timeBtwSpawn -= Time.deltaTime;
      }
  }

  private void SpawnNextObstacle()
  {
          lastInstantiatedObjectIndex = (lastInstantiatedObjectIndex + 1) % obstaclePatterns.Length;

          // Get the renderer to change its sorting order
          Renderer renderer = Instantiate(obstaclePatterns[lastInstantiatedObjectIndex ], transform.position, Quaternion.identity).GetComponent<Renderer>();

          // Destroy oldest obstacle and decrease by 1 the sorting order of all the instantiated renderers
          if( instances.Count >= maxObstaclesCount )
          {
              GameObject oldObstacle = instances[0].gameObject;
              instances.RemoveAt( 0 ) ;
              Destroy( oldObstacle ) ;
              DecreaseSortingOrder( instances ) ;
          }

          // Change sorting order of newly instantiated object
          renderer.sortingOrder = instances.Count;
          instances.Add( renderer  );
  }

  private void DecreaseSortingOrder( List<Renderer> renderers )
  {
       for( int i = 0 ; i < renderers.Count ; ++i )
            renderers[i].sortingOrder = Mathf.Max( 0, renderers[i].sortingOrder - 1 );
  }

Comment
LoserMangaka

People who like this

1 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 LoserMangaka · May 01, 2019 at 09:20 AM 0
Share

Hello,

Thanks the help with the array :) it works!

As for what I meant with the 2nd problem.

Thanks to your help, it looks like this when spawning. there are some cases it overlaps but not all which breaks the connecting effect.

alt text

I want the last object that spawns be always on top of the previous object so it would seem connect like these. The problem with this approach is it is just one game object and not an array of prefabs. I can't use the sorting order because the last object in my array won't connect properly with the first one in my array. Sorry if it's hard to understand, the main point is just have the last spawned object in my array to be on top of the previous object spawned.

Thanks again so much for your help :)

alt text

avatar image Hellium LoserMangaka · May 01, 2019 at 10:24 AM 0
Share

I've edited my answer to add a way to change the sorting order of all the instantiated obstacles. Give it a try, but I haven't tested the code myself.

avatar image LoserMangaka Hellium · May 01, 2019 at 10:54 AM 0
Share

Thanks,

I tried using your updated answer.

there were 2 problems that I noticed.

1st that it spawned 2 gameobjects from the array at the same time, but the last spawn always stayed on top of the previous spawn.

alt text

2nd problem is that your script conflicted with the destroyer script of mine, which is made to destroy the game objects after a given time. Since this will be an endless runner, I put a lifespan on my game objects that go out of screen.

alt text

Thanks again for continuous help. Very appreciated :)

Show more comments
avatar image

Answer by Lionesse · Nov 25, 2020 at 11:09 PM

Why so complicated? You can use while loop inside IEnumerator to increase index number every second (or whatever value you would like) and use that number as function's parameter. I suppose you already have rather simple object pooling script that take cares of garbage collection anyway.

Comment

People who like this

0 Show 0 · 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.

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

228 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

Related Questions

Instantiate isnt working for spawner class 1 Answer

Using a jagged array to spawn a GameObject 1 Answer

How do I spawn a certain amount of objects randomly between 2 positions? 0 Answers

Trying to spawn enemies on only one path 1 Answer

Spawning limited GameObjects at a specific position not working 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