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
0
Question by KevinRF · Jan 06, 2015 at 11:17 AM · prefabrandomspawner

Random Prefab Spawner C#

Hello Guys I'm stock whit my first IOS 2D Game project, i need a Random Prefab Spawner Script in C#,

whit some public values, so i can put in my prefabs and then i just want the script to Instantly between 5 seconds randomly spawn between the all prefabs i put in :) please help me out here !

alt text

randomspawnerscript.png (58.4 kB)
Comment
Add comment · Show 3
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 KevinRF · Jan 06, 2015 at 11:09 AM 0
Share

i use this script now. thats just simple, spawn the number of my enemy prefab i put in.... but this is not the way i want , because when i hit the Start it spawn 100 num of enemies. when the 100 enemies are destroyed there is no more enemies to shoot at....

so...

i want my new spawner to every 3 - 4 seconds spawn Instantly random spawn between 5 different enemy Prefabs i got.

so my enemies can keep going on and on and on and on.. forever.. and ever

((($$anonymous$$y Old Enemy Spawner Script))

 public GameObject enemyPrefab;
 public float numEnemies;
 public float x$$anonymous$$in = 19F;
 public float x$$anonymous$$ax = 85F;
 public float y$$anonymous$$in = 3.5F;
 public float y$$anonymous$$ax = -4.5F;
 
 void Start () {


     GameObject newParent = GameObject.Find("1 - Background Elements");
     
     for (int i = 0; i < numEnemies; i++)
     {
         Vector3 newPos = new Vector3(Random.Range(x$$anonymous$$in, x$$anonymous$$ax), Random.Range(y$$anonymous$$in, y$$anonymous$$ax), 0);
         GameObject octo = Instantiate(enemyPrefab, newPos, Quaternion.identity) as GameObject;
         octo.transform.parent = newParent.transform;
     }
     
 }

}

avatar image Jason Neo · Jan 08, 2015 at 05:21 PM 0
Share

Hey! I was follow the guide above but I got an error :(

Assets/PlatformSpawner.cs(8,37): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `PlatformSpawner.platformPrefabs'

Any idea? Thank you!

 using UnityEngine;
 using System.Collections;
 
 public class PlatformSpawner : $$anonymous$$onoBehaviour {
 
     public GameObject [] platformPrefabs;
 
     GameObject platformPrefab = platformPrefabs[Random.Range(0, platformPrefabs.Length)];
 
     private void SpawnPlatform()
         {
                 Vector3 newPos = new Vector3 (3.5, 1.8, 0);
                 GameObject octo = Instantiate (platformPrefab, newPos, Quaternion.identity) as GameObject;
         }
 
     void Start() 
 {
         for (int i = 0; i < numPlatforms; i++) 
         {
             SpawnPlatform ();
         }
 }
     
     private float timeUntilSpawn = 0;
 
     public void Update()
 {
         timeUntilSpawn -= Time.deltaTime;
         if (timeUntilSpawn <= 0)
         {
             SpawnPlatform();
         }
 
 }
 }
 
avatar image Scribe · Jan 08, 2015 at 05:25 PM 0
Share

you can't choose a member of platformPrefabs until the code knows it has been initiated, try:

 public GameObject[] platformPrefabs;
 GameObject platformPrefab;
 private void SpawnPlatform(){
     if(platformPrefabs == null || platformPrefabs.Length < 1){
         return;
     }
 
     platformPrefab = platformPrefabs[Random.Range(0, platformPrefabs.Length)];
     Vector3 newPos = new Vector3 (3.5f, 1.8f, 0f);
     GameObject octo = Instantiate (platformPrefab, newPos, Quaternion.identity) as GameObject;
 }

3 Replies

· Add your reply
  • Sort: 
avatar image
5

Answer by Chris_Dlala · Jan 06, 2015 at 04:00 PM

Hi! Firstly, I only want to give you enough of an understanding so you can give writing what you want a go. I'm going to break down your problem into a number of steps:

  1. Choosing a random prefab to instantiate

  2. Create a spawn method

  3. Call the spawn method repeatedly

    Choosing a random prefab to instantiate

    o do this we need a public array of GameObjects (prefabs) to choose from. This is done by adding "[]" to the end of the variable type (it's usually best to make the array name a plural):

public GameObject[] enemyPrefabs;

Now to access an element or single prefab you pass in an index between 0 and the number of entries in the array or "`Length`" property. So to get a random entry you would use:

GameObject enemyPrefab = enemyPrefabs[Random.Range(0, enemyPrefabs.Length)];

Then you can use that variable to instantiate an enemy in the scene.

Create a spawn method

ecause you are now spawning enemies at the start of the game, and then periodically throughout the game, you should wrap this functionality in one method that you can call repeatedly whenever you require an enemy to be spawned. For example:

 private void SpawnEnemy()
 {
     Vector3 newPos = new Vector3(Random.Range(xMin, xMax), Random.Range(yMin, yMax), 0);
     GameObject octo = Instantiate(enemyPrefab, newPos, Quaternion.identity) as GameObject;
 }

 // Example of calling method in Start...
 
 for (int i = 0; i < numEnemies; i++)
 {
     SpawnEnemy();
 }


Call the spawn method repeatedly

or repeated spawn there are many ways to do this. What you suggest is simple, you want a countdown to each spawn. For this you simply need to add an Update method and a time variable to track how long until the next spawn. Subtract the delta time from your countdown, and when the countdown reaches

 public float spawnCooldown = 1;
 private float timeUntilSpawn = 0;

 public void Update()
 {
     timeUntilSpawn -= Time.deltaTime;
     if(timeUntilSpawn <= 0)
     {
         // Do your enemy spawns here
         ...
         // Reset for next spawn
         timeUntilSpawn = spawnCooldown;
     }
 }
 

I hope that helps explain how to approach what you wanted. =D

Comment
Add comment · Show 1 · 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 Chris_Dlala · Jan 06, 2015 at 04:22 PM 0
Share

Did that explain enough of what you needed? If so, could you accept this answer =D

avatar image
0

Answer by KevinRF · Jan 08, 2015 at 12:35 PM

Hey Thanks man, I toke me some time to understand it, but now it works and thats total awesome! , thank you very much ! you are the best !!!!!!!!! =D :)

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

Answer by SilentFootsteps · Aug 27, 2017 at 05:52 PM

What if you wanted to spawn the game objects, assigning their position to empty cells in a panel (UI layout)? Like adding random items to an inventory system for example.

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

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Random Spawn, Random Prefab 2 Answers

How can I make my prefab fire out at a random velocity every 2 secs 2 Answers

instantiate random prefabs based on player camera distance 1 Answer

Semi Random Monster Spawner 3 Answers

How to randomly generate prefab? 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