Hi.
I want when Player bullet collide to enemy, reduce enemy health. in other world :
I wrote below script and want if Player bullet collide to other.gameobject, only reduce enemy health that collide with Player bullet. but this code reduce all enemies health.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBullet : MonoBehaviour
{
static int[] EnemyHealth = new int[16];
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy1")
{
for (int a = 0; a < EnemyHealth.Length; a++)
{
EnemyHealth[a] -= 10;
}
}
}
}
can anyone help me?
Thanks.
That is because EnemyHealth is static. That means it will be the same for all instance of PlayerBullet. How is this setup and how is EnemyHealth assigned? Is there 16 enemies and EnemyHealth is supposed to represent each enemy? If that is the case then you need a way to identify the incoming enemies index in EnemyHealth and reduce the health of that index item not all in the loop.
I assigned EnemyHealth for each enemy with this code:
for (int a = 0; a < 16; a++)
{
enemy = Instantiate(EnemyPrefab[0], EnemyPosition[a].transform.position, Quaternion.identity);
EnemyHealth[a] = 20;
}
yes I need a way but I can’t find this way. I need reduce EnemyHealth for each enemy that collide with Player Bullet. but I don’t know what insert instead of other.gameObject in EnemyHealth[ ] like below code.
if (other.gameObject.tag == "Enemy")
{
EnemyHealth[other.gameObject] -= 10;
}
I would recommend EnemyHealth being controlled by a script on the enemy instead. For example, having EnemyHealth.cs script on the enemy and having a function on it to subtract health. Then when the bullet collides with the enemy, you can call other.gameObject.GetComponent().subtractHealth(float amount)
Thanks, it’s good idea and work very well.