Here is my code for an enemy in the game. Right now its in development so there are no spawners, however it should just appear in the game as I have inserted him into the scene. However, when I play test the enemy disappears? I have no idea whats going on. Code (CSharp): public class badguy : MonoBehaviour { public class Badguys { public int health; public float speed; public float distance; public int points; public Transform target; } Badguys Lanky = new Badguys(); // Start is called before the first frame update void Start() { Lanky.target = GameObject.FindGameObjectWithTag("player").GetComponent<Transform>(); Debug.Log("loaded"); } // Update is called once per frame void Update() { if (Vector2.Distance(transform.position, Lanky.target.position) > Lanky.distance) { transform.position = Vector2.MoveTowards(transform.position, Lanky.target.position, Lanky.speed * Time.deltaTime); } if (Lanky.health <= 0) { Destroy(gameObject); } } private void OnTriggerEnter2D(Collider2D col) { Hleath.health -= 1; Debug.Log("die player"); } public void hit(int damage) { Lanky.health -= damage; Debug.Log("i took damage"); } }
When you play test, can you still see the enemy listed in the hierarchy panel? If not, then something deleted the enemy game object. If it is there, it could be that the enemy is outside the camera view or behind something. Pause the game and switch to the scene view. Select the enemy in the hierarchy panel and ,with your mouse cursor over the scene view, press "f" on the keyboard. This will make the scene view camera focus on your enemy so you can see where it actually is.
I would check what kdgalla said as it is probably something in the Unity editor or another script. Also, I noticed your OnTriggerEnter2D function. This won't work as you aren't actually checking to see if it hits the player. throw in an IF statement under the TriggerEnter function like: if(col.gameObject.tag == "player") and then have the 2 lines of code removing health.
The value of the health field is initialized with zero, by default. Thus, your health check in line 32 evaluates immediately to true and the gameObject is removed on the first update call. My suggestion is to explicitly initialize health with some positive value. Hope that helps.