• 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 umairbadboybuddadn545 · Apr 01, 2020 at 09:19 AM · instantiateprefab

Its only instantiating one object

I am a beginner to Unity and I am following a tutorial, and on his game view, many clones of his Prefabs are spawning. when I run mine, only one clone appears (of my "platformPrefab", i think) Are there any errors or issues with my code? If you need more information to answer the question, ask underneath and i will provide Cheers

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class PlatformSpawner : MonoBehaviour {

 public GameObject platformPrefab;
 public GameObject spikePlatformPrefab;
 public GameObject[] movingPlatforms;
 public GameObject breakablePlatform;

 public float platform_Spawn_Timer = 1.8f;
 private float current_Platform_Spawn_Timer;

 private int platform_Spawn_Count;

 public float min_X = -2f, max_X = 2f;

 // Start is called before the first frame update
 void Start()
 {
     current_Platform_Spawn_Timer = platform_Spawn_Timer;
 }

 // Update is called once per frame
 void Update()
 {
     SpawnPlatforms();
 }

 void SpawnPlatforms()
 {

     current_Platform_Spawn_Timer += Time.deltaTime;

     if (current_Platform_Spawn_Timer >= platform_Spawn_Timer)
     {

         platform_Spawn_Count++;

         Vector3 temp = transform.position;
         temp.x = Random.Range(min_X, max_X);

         GameObject newPlatform = null;

         if (platform_Spawn_Count < 2)
         {

             newPlatform = Instantiate(platformPrefab, temp, Quaternion.identity);

         }
         else if (platform_Spawn_Count == 2)
         {

             if (Random.Range(0, 2) > 0)
             {

                 newPlatform = Instantiate(platformPrefab, temp, Quaternion.identity);

             }
             else
             {

                 newPlatform = Instantiate(
                 movingPlatforms[Random.Range(0, movingPlatforms.Length)],
                     temp, Quaternion.identity);

             }

         }
         else if (platform_Spawn_Count == 3)
         {

             if (Random.Range(0, 2) > 0)
             {

                 newPlatform = Instantiate(platformPrefab, temp, Quaternion.identity);

             }
             else
             {

                 newPlatform = Instantiate(spikePlatformPrefab, temp, Quaternion.identity);

             }

         }
         else if (platform_Spawn_Count == 4)
         {

             if (Random.Range(0, 2) > 0)
             {

                 newPlatform = Instantiate(platformPrefab, temp, Quaternion.identity);

             }
             else
             {

                 newPlatform = Instantiate(breakablePlatform, temp, Quaternion.identity);

             }

             platform_Spawn_Count = 0;

         }




     }

     //newPlatform.transform.parent = transform;
     current_Platform_Spawn_Timer = 0f; 



         } // spawn platform
 } // class
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
0

Answer by Drislak · Apr 01, 2020 at 01:24 PM

Hi @umairbadboybuddadn545, I didn't know where exactly the issue in your code was, so I rewrote the code and improved it to make it more flexible, and improve performance. I added comments to everything, if anything is not clear feel free to add me on Discord: Drissy#2509. Hope this helps you out.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlatformSpawner : MonoBehaviour
 {
     [Header("Spawn Properties")]
     [SerializeField]
     private bool _disabled = false;
     [SerializeField]
     private float _delayInSeconds = 1.8f;
     [SerializeField]
     private int _platformLimit = -1;
     [SerializeField]
     [Range(0f, 1f)]
     private float _specialPlatformChance = 0.1f;
     private List<GameObject> _spawnedPlatforms = new List<GameObject>();
 
     [Header("Position Properties")]
     [SerializeField]
     private float negativeOffset = -2f;
     [SerializeField]
     private float positiveOffset = 2f;
 
     [Header("Platform Properties")]
     [SerializeField]
     private List<GameObject> _platformTypes = new List<GameObject>();
     [SerializeField]
     private int _defaultPlatformIndex = 0;
 
     void Start()
     {
         // start timer in Coroutine, this will make it run as a seperate thread in the background increasing your game's performance
         StartCoroutine(SpawnTimer());
     }
 
     private GameObject CalculatePlatform()
     {
         // exit this method when the platform cap has been reached, with -1 being infinite
         if (_platformLimit != -1 && _spawnedPlatforms.Count >= _platformLimit) return null;
 
         // as Mod 0 doesn't work we have to build a special case for this one
         if (_spawnedPlatforms.Count == 0)
         {
             if (_defaultPlatformIndex == 0) return CalculateNormalPlatform();
             return CalculateSpecialPlatform(0);
         }
 
         
         // calculate which platform to spawn based on the number of spawned and number of platform types
         // e.g. 0 Mod 4 = 0 so we take the first type, 1 Mod 4 is 1 so we take the second type, 4 Mod 4 is 0 again so we are back to the first type
         if (_spawnedPlatforms.Count % _platformTypes.Count == _defaultPlatformIndex)
         {
             return CalculateNormalPlatform();
         }
         else
         {
             return CalculateSpecialPlatform(_spawnedPlatforms.Count % _platformTypes.Count);
         }
     }
 
     private GameObject CalculateSpecialPlatform(int index)
     {
         // generate random to check if we should instantiate a normal or special platform
         if (Random.Range(0f, 1f) <= _specialPlatformChance)
         {
             int indexOfPlatformToSpawn = index;
             return _platformTypes[indexOfPlatformToSpawn];
         }
         else
         {
             return CalculateNormalPlatform();
         }
     }
 
     private GameObject CalculateNormalPlatform()
     {
         return _platformTypes[_defaultPlatformIndex];
     }
 
     private void SpawnPlatform()
     {
         // create the GameObject by calculating the correct type
         GameObject platform = CalculatePlatform();
 
         // we should only spawn the platform when not null
         if (platform)
         {
             // create position Vector based on the PlatformSpawner's position, and generate the X-axis position randomly based on the provided offset
             Vector3 position = new Vector3(Random.Range(negativeOffset, positiveOffset), transform.position.y, transform.position.z);
             
             // I don't know what this does but this was the rotation found in your code
             Quaternion rotation = Quaternion.identity;
 
             _spawnedPlatforms.Add(Instantiate(platform, position, rotation));
         }
 
         // if this created platform exceeds the max limit remove the platform created first
         if (_platformLimit != -1 && _spawnedPlatforms.Count > _platformLimit)
         {
             Destroy(_spawnedPlatforms[0]);
             _spawnedPlatforms.RemoveAt(0);
         }
     }
 
     IEnumerator SpawnTimer()
     {
         // keep going until disabled
         while (!_disabled)
         {
             // delay the spawn of a platform
             yield return new WaitForSeconds(_delayInSeconds);
             SpawnPlatform();
         }
     }
 }
 
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.

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

250 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

Related Questions

I get an error message every time i run this script? Any ideas? 0 Answers

Unable to set position of instantiated prefab 1 Answer

I need help destroying a clone on function. 1 Answer

Instantiated object retains variable values 0 Answers

My code is instantiating many prefabs, i only want one. 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