- Home /
Access to int from another script
I'm trying to make a script that checks your health and removes a heart if it goes down, but I can't seem to access to the character script's health. It's the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Corazones : MonoBehaviour
{
public Personaje personaje;
public int SaludActual;
public int TopeVida;
// Start is called before the first frame update
void Start()
{
SaludActual = personaje.vidaActual;
}
// Update is called once per frame
void Update()
{
SaludActual = personaje.vidaActual;
if(SaludActual < TopeVida)
{
(this.gameObject).SetActive(false);
}
}
}
Answer by Devster2020 · Jul 06, 2021 at 02:21 PM
Hello @Sansvern
You need to change a few things..
First of all, the "Corazones" script will be move to a GameObject that can link all corazones.. just create a simple GO and call it "Corazones Manager", adding the corazones script.. it will be like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Corazones : MonoBehaviour
{
public Personaje personaje;
public GameObject[] corazonesList;
public int SaludActual;
public int TopeVida;
void Update()
{
this.SaludActual = personaje.vidaActual;
for(int i = 0; i < this.corazonesList.Count; i++)
this.corazonesList[i].SetActive(this.SaludActual >= (i+1));
}
}
Additional Hint: This is not the best way.. the best one is to avoid the continuously check in the "Update" method and just call a function like "UpdateCorazonesGUI" when the player lose or gain a life..
I also take this opportunity to give you some tips on the style of the code.. here are some changes that make it more readable and clean (Player script):
in the Update method
if(Inmune)
{
if(Time.timeSinceLevelLoad >= nextTimeKickInmune)
{
AcabarInmunidad();
}
}
can be changed to:
if(Inmune && Time.timeSinceLevelLoad >= nextTimeKickInmune)
AcabarInmunidad();
And this is the "Muerto" function optimized:
public bool Muerto()
{
return vidaActual <= 0;
}
it doesn't work, it tells me Type UnityEngine.GameObject[]' does not contain a definition for
Count'
it's a small mistake...... .Count is used for lists...arrays like what you're using use .Length
you can either use a list instead of array..or just replace Count with Length
Okay, it seems to work, finally a number goes from 3 to 0 on the script, but the hearts don't disappear yet
Your answer
Follow this Question
Related Questions
Healing Zone. 3D game 2 Answers
How do I create an undertale player health bar in C #? 1 Answer
Smoothly move 2D Sprite 2 Answers
Why my Photon Scripts must be in a subfolder? 0 Answers
Cannot convert type 'UnityEngine.GameObject' to 'GameObject' 1 Answer