Hello,
I’m very new to Unity and I had just written a script following youtube tutorials. Basically when I hover the mouse over to a food item and click on it the player should restore some hunger value but nothing happens when I clicked. Below is my code for the item, raycast manager, and player stats:
public class ItemProperties : MonoBehaviour
{
[Header("Your Consumables")]
public string itemName;
[SerializeField] private bool food;
[SerializeField] private bool healthPotion;
[SerializeField] private bool hygineProduct;
[SerializeField] private float value;
[SerializeField] private PlayerStats playerStats;
public void Interaction()
{
if (food)
{
playerStats.HungerBar.value += value;
}
else if (hygineProduct)
{
playerStats.HygineBar.value += value;
}
else if (healthPotion)
{
playerStats.HealthBar.value += value;
}
}
}
[B]Raycast script[/B]
[code=CSharp]public class RaycastManager : MonoBehaviour
{
private GameObject raycastedObj;
[Header("Raycast Settings")]
[SerializeField] private float rayLength = 10;
[SerializeField] private LayerMask newLayerMask;
[Header("References")]
//[SerializeField] private PlayerStats playerStats; add this line to ItemProperties script
[SerializeField] private Image crossHair;
[SerializeField] private Text itemNameText;
private void Update()
{
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, out hit, rayLength, newLayerMask.value))
{
if(hit.collider.CompareTag("Consumable"))
{
CrosshairActive();
raycastedObj = hit.collider.gameObject;
//Update UI name
itemNameText.text = raycastedObj.GetComponent<ItemProperties>().itemName;
if (Input.GetMouseButtonDown(0)) //left meanas left mouse button
{
Debug.Log("Pressed primary button.");
//reference to item properties to know what to do with items
raycastedObj.GetComponent<ItemProperties>().Interaction();
}
}
}
else
{
CrosshairNormal();
//item name back to normal
itemNameText.text = null;
}
}
void CrosshairActive()
{
crossHair.color = Color.red;
}
void CrosshairNormal()
{
crossHair.color = Color.white;
}
[B]PlayerStats script[/B]
public class PlayerStats : MonoBehaviour
{
public float health = 100;
public float hunger = 100;
public float hygine = 100;
public float deathRate;
public float hungerRate;
public float hygineRate;
public Slider HealthBar;
public Slider HungerBar;
public Slider HygineBar;
// Update is called once per frame
void Update()
{
/*stats bar*/
HealthBar.value = health;
HungerBar.value = hunger;
HygineBar.value = hygine;
hunger = hunger - (hungerRate * Time.deltaTime);
hygine = hygine - (hygineRate * Time.deltaTime);
if (health <= 0)
{
health = 0;
Debug.Log("Dead");
}
if (hunger <= 0 || hygine <= 0)
{
health = health - (deathRate * Time.deltaTime);
}
if (hunger <= 0)
{
hunger = 0;
}
if (hygine <= 0)
{
hygine = 0;
}
}
}