0% found this document useful (0 votes)
9 views2 pages

Unity Health and Damage System Script

Uploaded by

jlegno95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Unity Health and Damage System Script

Uploaded by

jlegno95
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

using System.

Collections;
using [Link];
using UnityEngine;
using [Link];

public class Health_and_Damage : MonoBehaviour


{
public int vida;
private GameObject[] corazonesVida;

public bool invencible = false;


public float tiempoInvencible = 1f;
public float tiempoFrenado = 0.2f;

[SerializeField]
private GuardarEscena _guardarEscena;

private void Start()


{
vida = 3;
corazonesVida[0] = [Link]("VidaUnGolpe");
corazonesVida[1] = [Link]("VidaDosGolpes");
corazonesVida[2] = [Link]("Vidas");
_guardarEscena =
[Link]("ControladorDeOpciones").GetComponent<GuardarEscena>();
}
public void RestarVida(int cantidad)
{
if (!invencible && vida == 3)
{
corazonesVida[0].SetActive(true);
corazonesVida[1].SetActive(true);
corazonesVida[2].SetActive(true);

StartCoroutine(Invulnerabilidad());
StartCoroutine(FrenarVelocidad());

}
else if (!invencible && vida == 2)
{
corazonesVida[0].SetActive(true);
corazonesVida[1].SetActive(true);
corazonesVida[2].SetActive(false);

StartCoroutine(Invulnerabilidad());
StartCoroutine(FrenarVelocidad());

}
else if (!invencible && vida == 1)
{
corazonesVida[0].SetActive(true);
corazonesVida[1].SetActive(false);
corazonesVida[2].SetActive(false);

StartCoroutine(Invulnerabilidad());
StartCoroutine(FrenarVelocidad());

}
else if (vida == 0)
{
// guardar esta variable en un objeto que sea comun entre escenas
//[Link] = new int(GuardarEscena);
//[Link]("ControladorDeOpciones");

GameOver();
}
}

void GameOver()
{

_guardarEscena.escenaanterior = [Link]().buildIndex;

[Link](4);
}

IEnumerator Invulnerabilidad()
{
invencible = true;
yield return new WaitForSeconds(tiempoInvencible);
invencible = false;
}

IEnumerator FrenarVelocidad()
{
var velocidadActual = GetComponent<Player>().playerSpeed;
GetComponent<Player>().playerSpeed = 0;
yield return new WaitForSeconds(tiempoFrenado);
GetComponent<Player>().playerSpeed = velocidadActual;
}
}

Common questions

Powered by AI

The 'GuardarEscena' component is used within the script to track and store the index of the previously active scene when transitioning between scenes. It is crucial for scene transition management because it allows the game to recall the last scene the player was in before transitioning, which can be used for returning to previous game states, handling level progression, or restoring player progress after events such as game over. By keeping this information persistent, it facilitates seamless navigation and continuity between levels .

The player's health status is visually updated using an array of GameObject references named 'corazonesVida', which corresponds to the player's life symbolized by heart icons. Depending on the current health value, the respective hearts are set to active or inactive. If the player has all three health points, all heart icons are active; with two health points, the third heart icon is deactivated; with one health point, only one heart icon remains active. The 'RestarVida' method manages these changes by checking the current health and updating the visual representation accordingly .

Setting the 'tiempoFrenado' variable to zero would make the speed reduction effect immediate and without duration, effectively disabling the speed reduction altogether. This might be used in gameplay to eliminate any temporary speed penalty after taking damage if the design goal is to maintain a constant game pace. Designers might choose to use this configuration to create a more fast-paced game environment where stopping the player momentarily is undesirable or to suit particular levels or challenges .

Coroutines in the 'Health_and_Damage' script play a crucial role in managing time-dependent actions such as invincibility and speed reduction. The 'Invulnerabilidad' coroutine toggles the player's invincibility state for a set time, while the 'FrenarVelocidad' coroutine temporarily reduces the player's speed. This approach is effective due to its non-blocking nature, allowing the game to continue running smoothly during these delays. Compared to using 'Update' with timers, coroutines offer more organized and readable code for handling sequences that involve time delays, reducing the complexity of state management .

The 'Health_and_Damage' class demonstrates common practices in structured game programming through its use of component-based architecture, encapsulation, and coroutine management. Unity's component system is leveraged by referencing GameObjects and components, promoting modularity and reusability. Encapsulation of behaviors like health management and invincibility within the class allows for isolated modifications and debugging without affecting other components. Coroutines are used to handle asynchronous processes, showcasing a preferred practice for managing time-dependent actions without freezing the game loop, illustrating effective resource management and smooth gameplay transitions .

The 'GameOver' method in the 'Health_and_Damage' class is triggered when the player's life reaches zero. This method assigns the current scene's build index to the 'escenaanterior' variable within the 'GuardarEscena' component, effectively storing it. It then loads the game over scene by calling 'SceneManager.LoadScene(4)'. Storing the previous scene index is significant as it allows the game to track which scene the player was on before dying, enabling features like resuming from the last checkpoint or scene-specific data management when retrying .

The 'Health_and_Damage' class manages the player's invincibility through a coroutine called 'Invulnerabilidad'. When the player takes damage, the coroutine is started, setting the 'invencible' flag to true, thereby preventing further damage for a duration defined by the 'tiempoInvencible' variable. After this period, 'invencible' is set to false, allowing the player to take damage again. The purpose of the 'tiempoInvencible' variable is to define the length of time the player remains invincible after taking a hit .

The script ensures that the player cannot lose health while in an invincible state by using the 'invencible' boolean flag. The 'RestarVida' function checks this flag before any health deduction operation. If 'invencible' is true, the player is temporarily immune to damage. This interaction also influences player speed by triggering the 'FrenarVelocidad' coroutine if the player takes damage when not invincible. Consequently, it not only orchestrates damage control but also affects the player's mobility during and after an invincibility period, maintaining balanced gameplay .

If the heart icons were updated inside the 'Update' function, they would be evaluated every frame, leading to unnecessary overhead and potential performance issues. Since the visual update of heart icons is only needed when the player's health changes, managing these updates within the 'RestarVida' method is more efficient. This conditional updating minimizes calculations, enhances performance, and ensures that changes to the UI are executed only when necessary. Thus, updating in 'Update' might cause a degrade in performance and a less responsive user experience due to potential frame rate drops .

Implementing the speed reduction effect via the 'FrenarVelocidad' coroutine offers the benefit of handling the reduction and subsequent restoration of player speed within a concise and organized flow, which is more readable and maintainable. It leverages Unity's coroutine system to execute time-based sequences efficiently without blocking the main thread. However, this method introduces slight complexity because it requires careful management of coroutine lifecycle and dependencies. Applying the effect directly in response to a damage event could reduce complexity and latency in some scenarios but might lead to less organized code structure, making maintenance challenging as the game logic becomes more intricate .

You might also like