Vurtle
Vurtle

Reputation: 13

Untiy Health System

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveProjectile : MonoBehaviour
{

    public Rigidbody2D projectile;

    public float moveSpeed = 10.0f;



    // Start is called before the first frame update
    void Start()
    {
        projectile =  this.gameObject.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        projectile.velocity = new Vector2(0,1) * moveSpeed;
    }

    void OnCollisionEnter2D(Collision2D col){
        if(col.gameObject.name == "Enemy"){
            gameObject.name == "EnemyHeart5".SetActive(false);
        }
        if(col.gameObject.name == "Top"){
            DestroyObject (this.gameObject);
        }

    }
}

This is the code to my player projectile. On collision i tried to reference it to a game object i have called playerheart and it doesnt seem to work out the way i wanted it to.

Im trying to make a health system where if my bullet collides with the enemy game object the health would decrease by one. Im pretty new to Unity and im confused on how to target the hearts when the bullets collide.

Upvotes: 0

Views: 181

Answers (1)

Pruthvi
Pruthvi

Reputation: 85

I'm assuming "EnemyHeart5" is a GameObject inside Enemy as child gameobject. Correct?

Issue here is when the collision takes place, it recognize "Enemy" gameobject and won't have access to "EnemyHeart5" for disabling it. I'd suggest you to add simple EnemyManager script into your enemy which manages your enemy health and health related gameobject (ie. EnemyHearts which you are displaying). When collision takes place, access that EnemyManager component and change health value.

void OnCollisionEnter2D(Collision2D col){
    if(col.gameObject.tag == "Enemy"){
        col.gameObject.GetComponent<EnemyManager>().health =-1;
    }

Now, in the update method of EnemyManager you check the health value and disable EnemyHealth5 component.

Also, use "tag" in collision instead of "name". name will create issues when you have multiple enemies in the game. Make sure you add tag in enemy gameobject if you are using it.

Hope this helps, let me know how it goes.

Upvotes: 1

Related Questions