I want the, let’s say, 10 obstacles, each with 10% chance of spawn, to generate when the “player” is close enough, and then the obstacle to delete itself when the “player” is far enough. I would like this to be an infinite, scored type game.
your help would be greatly appreciated, I will not forget to mention you in the credits, and if the game becomes successful, I will look for you to repay you.
Create an empty game object that has a bunch of cubes attatched to it. These cubes are your spawn points. (Disable mesh renderer and box collider)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SpawnScript : MonoBehaviour {
public Transform Crate;
public Transform Gem_Blue;
private GameObject[] SpawnTiles;
public List<Transform> AvailableTiles;
public List<Transform[]> SpawningTiles;
public float SpawnTimer = 3.5f;
void Start() {
SpawnTiles = new GameObject[7];
SpawnTiles = GameObject.FindGameObjectsWithTag ("Spawner");
AvailableTiles = new List<Transform> ();
SpawningTiles = new List<Transform[]> ();
foreach(GameObject go in SpawnTiles) {
AvailableTiles.Add(go.transform);
}
StartCoroutine ("HandleSpawns");
}
private int spawnLimit = 4;
private float gemRatio = 22.5f;
private float crateRatio = 80.0f;
void CalculateSpawns() {
foreach(Transform currentTile in AvailableTiles) {
if(SpawningTiles.Count < spawnLimit) {
int rolled = Random.Range (0, 100);
Debug.Log (rolled);
if(rolled < gemRatio) {
SpawningTiles.Add (new Transform[] { currentTile, Gem_Blue });
} else if(rolled < crateRatio) {
SpawningTiles.Add(new Transform[] { currentTile, Crate });
}
}
}
}
void ClearSpawns() {
SpawningTiles.Clear ();
}
void SpawnEntities() {
int SpawnTile = 0, SpawnEntity = 1;
foreach (Transform[] listData in SpawningTiles) {
listData[SpawnTile].GetComponent<SpawnTileScript>().SpawnEntity(listData[SpawnEntity]);
}
ClearSpawns ();
}
IEnumerator HandleSpawns() {
while (true) {
CalculateSpawns ();
SpawnEntities ();
ClearSpawns ();
yield return new WaitForSeconds (SpawnTimer);
}
}
}
Attatch this to each of the “Spawn Tiles”
using UnityEngine;
using System.Collections;
public class SpawnTileScript : MonoBehaviour {
void Start() {
}
public void SpawnEntity(Transform Entity) {
Instantiate (Entity, transform.position, transform.rotation);
}
}
You should be able to do the rest. I just made a game like this yesterday. So thats where these scripts are from
Don’t forget to clear the list before each respawn, etc.
Keep in mind… Don’t try to move towards everything.
Make the objects you spawn move towards the left at a constant rate.
Don’t let the character move anywhere besides up and down.
Once they hit the left side of the screen, destroy them.
Example
// Update is called once per frame
void Update () {
if (transform.position.x < -3.5)
GameObject.Destroy (this.gameObject);
}
void FixedUpdate() {
rigidbody.velocity = new Vector3 (-01.25f, 0, 0);
}
You don’t want to instantiate and destroy the objects, that’s a waste of resources. Instead, create a pool of objects offscreen. So, 3 of this obstacle, 3 of that obstacle, etc. When you want to use one, position it a certain distance ahead of your character. Once you pass the obstacle and it is offscreen, you can just leave it until you need to use it again. You’ll need to keep track of which obstacles are active and which are not active. The Flappy Bird game I did recently only uses 4 obstacles total.
I achieved it by having 6 pipes (3 top and 3 bottom) and having a static player. What happens is when they go off the screen to the left, they get placed behind the last lot of pipes with a random height applied. Repeat the process and you have a continuous level of pipes without having to destroy and create new objects over and over again.
The way it differs from that though, is that script will put the pipes behind one another so you need to work in a spacing variable and having top childs and bottom childs/
“i’m beginner in code for unity” - I only started using unity myself a week ago
That’s kind of how I did it. Once an obstacle was a certain distance off screen, I moved it behind the last obstacle in front of the character. Since I had a reference to each obstacle, I’d take the last obstacles position ( in front of the character ) and add a constant value to the x position. That way they stay evenly spaced. I’d also give it a random height with a set range.
I attempted several different methods, but they all lags… even when I am running them on PC. I tried instantiating and destroying, I tried putting 5 prefabs outside the game camera and position the vertical gap randomly and move them via transform. See below:
Please teach me how! I have 25 obstacles, I want them to randomly generate in front of player, in a 2d fashion, without lag. Can you help me out with this?
I use a script on each obstacle. Each script has a reference to the obstacle directly to the left of it. Then I do this:
Check to see if the obstacle is less than a certain x position ( to the left of the player ).
If it is less than that x position, reset its x position so that it is a set distance to the right of the obstacle it has a reference to. This reference obstacle should be the obstacle located furthest to the right at that point. So take your reference obstacle’s position, add a constant value to its x position and set the current obstacles x position to the new position.
Change the obstacles y position.
And that’s it. If you are experiencing lag, it might be a result of having 25 obstacles. I mentioned before that I am only using 4 obstacles total. If that’s not the case, one of your other scripts is causing the lag. In the update function, I am using a state machine to check the state of the game. If you don’t know what a state machine is, there should be a ton information around the web that explains what it is. I use a switch statement for each possible state the game can be in and then call a function based on the current state.
You could buy our plugin “Core GameKit” on the Asset Store. Currently 75% off for only $15! It has built in pooling (mentioned above), combat system (hit points and attack points), spawners - including triggered spawners that can spawn from a collision or many other events, and tons more. You won’t have to write any code, it’s all done through custom inspectors. And we have 61 reviews with a 5 star average. Good time to pick it up for sure Pool Manager is $30 and only does pooling.
There’s a feature there called Prefab Pools where you can create a group of weighted prefabs for spawning so that prefab A will spawn 5 times as often as prefab B and things like that. That’s what you were asking about in the OP.
There are also several auto-despawners built in (when going offscreen, leaving trigger, etc). It should take care of everything you want and much more.
I’m new to Unity and C# so ,Can you please explain the code that you have posted? What does gemratio and crateratio refer to in the code? Are crate and gem_blue the objects that you are going to spawn? Baiscally can you explain everything please?