Hello!
This may be a difficult and very unique question. I have 2D sprites that are slowly falling down for my player to catch them. After a while (theoretically), if my player catches all the objects I created in Unity, there will be nothing left to catch. How do I randomly generate objects and make them fall from different places, with different tag values? So I have a few tags (PickUp, TestSolid, Die), and I want them to be attached randomly to the falling objects that are automatically generated. I have already made an area under the player where the objects will be deactivated (to save RAM and FPS), but now how do I keep generating them so they keep coming down forever? Please make your answer specific, and I don’t know too much about scripting. THANK YOU VERY MUCH!!!
You need to lookup InvokeRepeating(), Instantiate() and Random.Range().
Here is how you would write it in javascript:
private var locationsToSpawn:GameObject[];
private var counter:float = 0;
var listOfPossibleTags:String[];
var objectToSpawn:GameObject[];
var timeBetweenSpawns:float = 3.0f;
function Start(){
locationsToSpawn = GameObject.FindGameObjectsWithTag("SpawnLocation");
}
function Update(){
counter+= Time.deltaTime;
if(counter > timeBetweenSpawns){
var object:GameObject = Instantiate(objectToSpawn[Random.Range(0, objectToSpawn.Length)], locationsToSpawn[Random.Range(0, locationsToSpawn.Length)], Quaternion.identity);
object.gameObject.tag = listOfPossibleTags[Random.Range(0, listOfPossibleTags.Length)];
counter = 0;
}
}
Here is how you would do it in C#:
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
private GameObject[] locationsToSpawn;
private float counter = 0;
[SerializeField] string[] listOfPossibleTags;
[SerializeField] GameObject[] objectToSpawn;
[SerializeField] float timeBetweenSpawns = 3.0f;
void Start (){
locationsToSpawn = GameObject.FindGameObjectsWithTag("SpawnLocation");
}
void Update (){
counter+= Time.deltaTime;
if(counter > timeBetweenSpawns){
GameObject spawnedObject;
spawnedObject = Instantiate(objectToSpawn[Random.Range(0, objectToSpawn.Length)], locationsToSpawn[Random.Range(0, locationsToSpawn.Length)].transform.position, Quaternion.identity) as GameObject;
spawnedObject.gameObject.tag = listOfPossibleTags[Random.Range(0, listOfPossibleTags.Length)];
counter = 0;
}
}
}
I have updated by C# script since some stuff with it was incorrect.