Hello, new to unity and coding. I have prefabs that I spawn into the scene, and touching them makes the player take damage. I have a component in my “DamageControl” script that calls a script from a gameobject that will have the player lose health, this gameobject also controls the text that shows the player how much health they have.
The problem is that I have no idea how to put this gameobject into the prefab upon starting the game. Setting the gameobject as a prefab doesn’t work because then the text doesn’t update, nor does the game end when the players health reaches 0.
Here is the code for the scripts that I am working with:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageControl : MonoBehaviour
{
[SerializeField] public float circleDamage;
[SerializeField] private HealthControl HealthController;
void Start() {
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("Player"))
{
Damage();
}
}
void Damage()
{
HealthController.playerHealth = HealthController.playerHealth - circleDamage;
HealthController.UpdateHealth();
this.gameObject.SetActive(false);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HealthControl : MonoBehaviour
{
public float playerHealth;
[SerializeField] private Text healthText;
public void UpdateHealth()
{
healthText.text = playerHealth.ToString("0");
}
private void Update() {
if(playerHealth == 0)
{
SceneManager.LoadScene("gameover");
}
}
}
Thank you.