Reputation: 21
I asked this on Unity discussions, but I figured I should ask here too in case anybody has advice.
I'm creating a 2D maze game where I have power ups and traps in place. I have multiple spawn points that go in an array for the script to choose from, so not random, and as soon as the player collides with a powerup or trap, I need it to go away as its been 'used' and spawn elsewhere on another spawn point. I figured out how to manage spawning a singular prefab, by directly specifiying it as a field in the inspector. Now I need to figure out how to make it work with multiple kinds of spawning objects that each have their own count of them there need to be at once in the scene (defined as initial count in the inspector and script).
I have an empty object in my game called game manager that essentially manages the overall aspects of the game such as saving and loading data, and also spawning different kinds of objects. I'll put the script of one example of a prefab I need to spawn, a health buff, and the game manager script, this is how I've done it to make it for one specific spawnable object, now I need to do multiple by defining a general code for prefabs (maybe through an objects list I can add on the inspector? I don't know how to do that though.) Any and all help is appreciated :)
Game Manager Script:
[Serializable]
public class GameManager : MonoBehaviour
{
public GameObject prefab; // the prefab that should respawn
public Transform[] spawnPoints; // an array of the transform portion of the spawnpoints
public int initialPrefabCount; // the count that the prefab should maintain and starts at
public int currentPrefabCount; // the count that changes and is monitered
void Start() {
// spawn the initial prefabs
for (int i = 0; i < initialPrefabCount; i++) {
SpawnPrefab();
}
}
void SpawnPrefab() {
if (currentPrefabCount >= initialPrefabCount) {
return; // Limit reached, no need to spawn more prefabs
}
// Randomly select a spawn point from the array
Transform spawnPoint = spawnPoints[UnityEngine.Random.Range(0, spawnPoints.Length)];
// Instantiate the health buff prefab at the spawn point
Instantiate(prefab, spawnPoint.position, Quaternion.identity);
currentPrefabCount++; // Increase the count of the prefabs by one
}
public void PrefabDestroyed() {
currentPrefabCount--; // decrease the current count by one to show a prefab has been destroyed
SpawnPrefab(); // call the function to spawn again
}
}
Health Buff Script:
public GameManager gameManager;
void Start()
{ // checks whether any reference in the game editor is null
if (gameManager == null) {
Debug.LogWarning("GameManager reference is not assigned.");
gameManager = FindObjectOfType<GameManager>(); // Find GameManager in the scene
}
}
private void OnTriggerEnter2D(Collider2D collision) {
// check if collision is with player or not
if(collision.gameObject.tag == "Player"){
Debug.Log("Player collided with health buff.");
// collision data
Destroy(gameObject); // destroyes the health buff
// tells the game manager that a prefab has been destroyed and to spawn another
gameManager.PrefabDestroyed();
}
}
Upvotes: 1
Views: 243
Reputation: 4591
Make a base class for your spawnable items. All spawnable items should extend this base class. Add an OnPickup
method that can be overridden by derived classes.
public class SpawnableItem : MonoBehaviour
{
public ItemSpawner itemSpawner; // ref to the object that spawned this, should be replaced by event that is subscribed to by the spawner
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.CompareTag("Player"))
{
OnPickup();
}
}
protected virtual void OnPickup()
{
itemSpawner.ItemDestroyed();
Destroy(gameObject);
}
}
The item spawner is the code you posted as the class GameManager
in your question. Make a new class called ItemSpawner
, copy the code from your GameManager class that handles the item prefab stuff.
public class ItemSpawner : MonoBehaviour
{
public SpawnableItem spawnableItem; // <- Replaces "GameObject prefab;"
// other fields..
private void SpawnItem()
{
// do checks and such..
// spawn item
//
var item = Instantiate(spawnableItem, spawnPoint.position, Quaternion.identity);
item.itemSpawner = this; // set the spawner ref so the item can inform when destroyed
// another option is to use events instead of concrete ref
}
public void ItemDestroyed()
{
// item was destroyed, decrement count and such
}
}
Make specific items extending the SpawnableItem
base class. Override the OnPickup
method to do something specific when this item is picked up.
public class HealthBuffItem : SpawnableItem
{
protected override void OnPickup()
{
base.OnPickup(); // make sure to call this so the base class code will execute
// If you don't want the base class code to execute, exclude this line
// Do something specific here when item is picked up
}
}
This works great if you want one spawner to handle a single item. You would create multiple spawners in the scene.
If you want a single spawner to handle all the items, create a new data class (or scriptable object!) for the prefab data that contains the spawnable object and its associated data. Create an array of this data class on the spawner in place of the single prefab and utilize that array when spawning and handling destroyed items.
[Serializable]
public class SpawnableItemData
{
public SpawnableItem item;
public int initialCount;
public int currentCount;
// etc..
}
When an item is picked up, you will need to pass the item that was picked up back to the spawner and the spawner will have to determine when item it was in order to decrement the correct count. You could also simply pass the data class to the item when it is spawned and the item can manage the data, leaving the spawner out of it.
Upvotes: 0