Method to take life of the Player does not work

Asked

Viewed 244 times

2

I’m making a script for take the player’s life when something collides with it, I’ve reviewed the code dozens of times and can’t find the error.

The collision code is tied to the 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 the one in 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);
}
  • Rafa Arruda, I edited your question, I removed some tags and changed the title, if you want, you can reverse it. Or edit it.

1 answer

1


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

I recommend giving a look at this videothat will help a little on the subject, and solve all your problems.

Some guidelines:

1.

ph = gameObject.AddComponent<PlayerHealth> ();

You’re adding a component whenever you bump into something. I recommend you first check if it is the player, and be it you take the Playerhealth from it.

Use other.gameObject.GetComponent to catch the one you bumped into.

2.

Destroy (gameObject);

You want to take life, or destroy the object?

3.

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

  • 1

    Oh yes, I am using the same principle of that code in another game, so I was having difficulties. But I managed to solve by changing the code of Playerhealth to the control script. Now it has worked right. Another problem I was having is regarding calling the slider in the script, I got it in a different way. Then I’ll send you here to take a look. Vlw Nils. Your videos are great!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.