The question is answered, right answer was accepted
Why ain't my Code working?
I trying to have a system that spawns enemies and then wait till all dead to spawn more. When an enemy dies it suppose to lower enemyalive; No matter how the enemy dies I want it to drop enemyalive by 1 and if it hits player in collision that just game over & got that handled.
here is health script:
public float health;
public Controler Con; // here i tried linking it to the Controler script
void OnTriggerEnter2D(){
health -= 1;
}
void Update () {
if (health <= 0) {
Die ();
}
}
void Die(){
if (gameObject.tag == "Enemy") {
Con.enemyalive -= 1; // here it suppose to access the script Controler and minus the number by 1
}
Destroy (gameObject);
}
}
if anyone can fix this or know better way to check if none exists please say i already tried one way but it only works if not null;
Answer by codytremblay · May 28, 2017 at 04:20 PM
after several hours of yelling. I just made a script just for enemy.
here the code
public int health;
public Controler Con;
void Start(){
Con = GameObject.Find("Player").GetComponent<Controler>(); // I was missing this part ty oscarklm for giving me it.
}
void OnTriggerEnter2D(){
health -= 1;
}
void Update () {
if (health < 1){
Die();
}
}
void Die(){
Con.enemyAlive -= 1; // here it takes 1 away so i see who is alive or dead
Destroy(gameObject);
}
Glad you got what i meant with my example. Happy coding!
Answer by oscarklm · May 28, 2017 at 11:20 AM
Hey!
Looks like you're making this a bit confusing for yourself. I've attached a way of doing this for you. Hopefully that will help you achieve what your trying to do.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthScript : MonoBehaviour {
public int health; // You are better off using integer for your health, floats are mostly used for more precise measurements
public Controller con;
// Use this for initialization
void Start () {
// We need to find a player with the Controller attached and set con to that controller, to be able to use it properly
con = GameObject.Find("Player").GetComponent<Controller>();
}
// Update is called once per frame
void Update () {
if (health <= 0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
con.enemiesAlive -= 1; // Subtracting 1 from enemiesAlive
}
}
}
this script is on many things. If I did your way no one could lose health it would only end in GameOver so no use for levels.
I wasn't telling you how to code what you're trying to do. Only explaining you the importance of setting the con to the component of Controller attached to a GameObject :)
// We need to find a player with the Controller attached and set con to that controller, to be able to use it properly con = GameObject.Find("Player").GetComponent();