Hi!
I’ve been studying unity recently. And through few tutorials I found a problem.
I developed these 2 scripts below (PlayerController and ScoreManager). But I would like to create a statement in the ScoreManager scripting that checks if the player’s health is greater than 0.
I thought about creating a statement that says “if health is greater 0 then increase the score” but how do I access the player health through the ScoreManager script? How do I make a reference to the PlayerController and access the health?
The playercontroller script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{
private Vector2 targetPos;
public float Xincrement;
public float maxLeft;
public float maxRight;
public int health = 5;
public float maxHeight;
public float minHeight;
public float speed;
public float Yincrement;
public int numberOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
public GameObject gameOver;
void Start()
{
}
void Update()
{
if(health <= 0)
{
gameOver.SetActive(true);
Destroy(gameObject);
}
for(int i = 0; i < hearts.Length; i++)
{
if(i < health)
{
hearts.sprite = fullHeart;
}
else
{
hearts.sprite = emptyHeart;
}
if (i < numberOfHearts)
{
hearts.enabled = true;
}
else
{
hearts.enabled = false;
}
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.RightArrow) && transform.position.x < maxRight)
{
targetPos = new Vector2(transform.position.x + Xincrement, transform.position.y);
}
else if (Input.GetKeyDown(KeyCode.LeftArrow) && transform.position.x > maxLeft)
{
targetPos = new Vector2(transform.position.x - Xincrement, transform.position.y);
}
else if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
}
The ScoreManager script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
public Text scoredacerto;
public Text highScoreText;
public float scoreCount;
public float highScoreCount;
// Start is called before the first frame update
void Start()
{
if (PlayerPrefs.HasKey("Highscore"));
{
highScoreCount = PlayerPrefs.GetFloat("Highscore");
}
}
// Update is called once per frame
void Update()
{
if(scoreCount > highScoreCount)
{
highScoreCount = scoreCount;
PlayerPrefs.SetFloat("Highscore", highScoreCount);
}
scoredacerto.text = "Score: " + scoreCount;
highScoreText.text = "HighScore:" + highScoreCount;
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Obstacle"))
{
scoreCount++;
}
}
}