Player's lifeless method does not work

2

I'm doing a script to take life out of the player when something collides with it, I've reviewed the code dozens of times and can not find the error.

The collision code is tied to enemies:

PlayerHealth ph; 
public int danoAtaque = 10;

void OnTriggerEnter (Collider other)
{
    ph = gameObject.AddComponent<PlayerHealth> ();

    if (other.tag == "Player") 
    {
        Debug.Log ("Entrou no Player");
        ph.TakeDamage(danoAtaque);
        Debug.Log ("Tirou vida");

        if (ph.vidaAtual <= 0) 
        {
            Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver ();
            Destroy (other.gameObject);
            Debug.Log ("Morreu");
        }
     }

    if (other.tag == "Boundary" || other.tag == "Enemy") {
        return;
    }

    if (explosion != null) {
        Instantiate (explosion, transform.position, transform.rotation);
    }
    gameController.AddScore(scoreValue);        
    Destroy (gameObject);

}

This other code is what is in the Player:

static int vidaInicial = 100;
public int vidaAtual;

public Slider healthSlider;
public Image damageImage;
public float flashSpeed = 5f;
public Color flashColour = new Color(1f, 0f, 0f, 0.1f);

void Awake ()
{
    vidaAtual = vidaInicial;
}

public void TakeDamage (int amount)
{
    Debug.Log("Chamou Funçao");
    vidaAtual -= amount;
    Debug.Log("Deu Dano");   
}

void OnGUI()
{
    GUI.Label (new Rect (10, 10, 100, 20), "Vida: " + vidaAtual);
}
    
asked by anonymous 26.05.2015 / 21:51

1 answer

1

There are some mistakes, and some things that could improve.

I recommend giving a look at this video that will help a lot as the subject, and resolve all your problems.

Some guidelines:

1.

ph = gameObject.AddComponent<PlayerHealth> ();

You're adding a component every time you hit something. I recommend you first check if it is the player, and being for you you get PlayerHealth from it.

Use other.gameObject.GetComponent to get the one you crashed.

2.

Destroy (gameObject);

Do you want to take life, or Destroy the object?

3.

Remember that there is a difference between using gameObject and other.gameObject .

    
27.05.2015 / 01:03