using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enitity : MonoBehaviour
{
[SerializeField] private float StartingHealth;
private float Health;
public float health
{
get
{
return health;
}
set
{
health = value;
Debug.Log(health);
if (health <= 0f)
{
Destroy(gameObject);
}
}
}
// Start is called before the first frame update
void Start()
{
Health = StartingHealth;
}
}
Because you are accessing the poperty itself.
“health” is your property name and “Health” is the actual variable. You you wanna set and get the later inside of your property getter and setter.
Btw. capitalization is inverted compared to typical coding conventions. Normally the property is capitalized.
It’s spelled ‘StackOverflow’ not ‘StackedOverflow’. Stack in this is referring to the ‘call stack’ which is the memory that is allocated for each method/function call. Each function stacks on top of the other and if those functions recurse in on themselves the stack grows infinitely overflowing the maximum size of the stack.
It’s spelling mistakes like these that may lead to your issues.
private float Health;
public float health
{
get
{
return health; //note the case of the 'h' vs 'H'
A lot of programmers pick some standard between their backing fields and their properties. Some examples include:
lower-case backing, upper case property:
private float health;
public float Health
{
get
{
return health;
Or the underscore for backing (this is my preferred):
private float _health;
public float Health
{
get
{
return _health;
Or the m_ (m for member… this is what I’ve noticed Unity internally does a lot):
private float m_health;
public float Health
{
get
{
return m_health;
I personally like the _ and m_ because it’s REALLY obvious which is the backing. Where as the case difference can be easily overlooked when reading quickly.
Also it’s not a good practice to do “heavy work” in a property setter (in your case destroying a game object). An object trying to set the value won’t guess that by just setting a value to a property it could destroy the whole object! As a general rule, a setter should only do work on the value it got assigned (clamp it being the most common).
This would be better:
// No need for a backing field
public float Health { get; private set;}
public void TakeDamage(float damage)
{
Health -= damage;
if (Health <= 0)
Destroy(gameObject);
}
This is a lot better, and when a object calls the method TakeDamage(), the intent is very clear.