I’ve been trying for days now to get a simple respawn system working for an FPS I’m working on. Basically, I want ammo boxes to spawn in fixed locations when the level starts, and to respawn after a short time, in the same place, when the player collects them. If you’ve ever played Goldeneye or Perfect Dark multiplayer, it’s a similar system to that I’m trying to implement.
The code for one of these crates (using prefabs) is below…
using System.Collections;
using UnityEngine;
public class AmmoRespawn1 : MonoBehaviour
{
public AudioSource AmmoSound;
public bool isSpawned;
public GameObject spawnedCrate;
public GameObject spawningCrate;
public Transform spawningPoint1;
private void Start()
{
Instantiate(spawnedCrate, spawningPoint1.position, spawningPoint1.rotation);
isSpawned = true;
}
private void Update()
{
while (isSpawned == false)
{
spawnedCrate.gameObject.SetActive(true);
isSpawned = true;
}
}
void OnTriggerEnter(Collider other)
{
AmmoSound.Play();
Debug.Log("Picked up some ammo");
if (GlobalAmmo.LoadedAmmo == 0)
{
GlobalAmmo.LoadedAmmo += 10;
}
else
{
GlobalAmmo.CurrentAmmo += 10;
Destroy(spawnedCrate);
}
spawnedCrate.gameObject.SetActive(false);
StartCoroutine("Respawn");
}
IEnumerator Respawn()
{
yield return new WaitForSeconds(10);
isSpawned = false;
}
}
spawningPoint1 is a cube without rendering that’s been placed in the level.
When I try to run this code, I get some odd results. It seems to spawn huge numbers of crates, and when my FPS camera makes contact, I get thousands of ammo added to my total, when it should only be 10 for each crate. It also often makes the camera fall through the floor where the crate is.
Also, the crate won’t appear at the start of the level unless I’ve already dropped an instance of the prefab spawningCrate in, even though every tutorial I’ve watched suggests I don’t need to do this.