Created
January 13, 2022 22:47
-
-
Save ayyobro/44c270a90a85fa778e24b145c669af48 to your computer and use it in GitHub Desktop.
Example of HealthCollectable prefab script for respawning itself
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Screenshot of unity configuration for the script on the prefab: