Skip to content

Instantly share code, notes, and snippets.

@ayyobro
Created January 13, 2022 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayyobro/44c270a90a85fa778e24b145c669af48 to your computer and use it in GitHub Desktop.
Save ayyobro/44c270a90a85fa778e24b145c669af48 to your computer and use it in GitHub Desktop.
Example of HealthCollectable prefab script for respawning itself
using System.Collections;
using UnityEngine;
public class HealthCollectable : MonoBehaviour
{
public float health = 20.0f;
public float rotationSpeed = 25.0f;
public float cooldown = 1.0f;
private bool wasUsed = false;
public GameObject healthPrefab;
private GameObject player;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
healthPrefab = gameObject;
}
// Update is called once per frame
void Update()
{
transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed);
}
private void OnTriggerEnter(Collider other)
{
PlayerManager pManager = player.GetComponent<PlayerManager>();
if (other.gameObject.CompareTag("Player") && pManager.health < 100)
{
pManager.Heal(health);
healthPrefab.SetActive(false);
wasUsed = true;
}
}
IEnumerator GenerateNewHealthPrefab()
{
Debug.Log("Coroutine!!");
if (wasUsed)
{
Debug.Log("About to wait!!");
yield return new WaitForSeconds(cooldown);
healthPrefab.SetActive(true);
wasUsed = false;
}
}
private void FixedUpdate()
{
StartCoroutine(GenerateNewHealthPrefab());
}
}
@ayyobro
Copy link
Author

ayyobro commented Jan 13, 2022

Screenshot of unity configuration for the script on the prefab:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment