Hey guys im trying to make a script where the code takes all the objects in the game and deals 100 damage to them. I use an array to get all the objects however i dont know how to get all their components at once and deal damage to them. If you guys could help it would be much appreciated. Thanks Beforehand
Code:
var explosion : GameObject;
var BlastRadius : int = 10;
var Damage : int = 100;
var Radius : float = 10.0;
var Enemy : AIdamage;
var Enemies : GameObject[];
private var center : Vector3;
private var hitTarget : GameObject;
function update (){
Enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
function OnCollisionEnter(hitTarget : UnityEngine.Collision)
{
Enemies.GetComponents("AIdamage").CurrentHealth -= Damage;
}
c# example of how to access the AIDamage classes and check for hits with Physics.OverlapSphere:
using UnityEngine;
using System.Collections;
public class ExplosionExample : MonoBehaviour
{
public GameObject explosionEffect;
public float damage=5, blastRadius=10;
bool firstCollision=true;
void OnCollisionEnter(Collision col)
{
if(firstCollision)
{
firstCollision=false;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, blastRadius);
for(int i=0;i<hitColliders.Length;i++)
{
if(hitColliders[i].CompareTag("Enemy"))
{
hitColliders[i].GetComponent<AIDamage>().CurrentHealth -= damage;
}
}
}
//explosionEffect
}
}
if you want to avoid using GetComponent too much for some reason, one way to do so is to use a dictionary from System.Collections.Generic to store the AIDamage classes
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ExplosionExample2 : MonoBehaviour
{
public GameObject explosionEffect;
public float damage=5, blastRadius=10;
Dictionary<Collider,AIDamage>enemyScripts=new Dictionary<Collider, AIDamage>();
void Start ()
{
GameObject[] hitTargets;
hitTargets=GameObject.FindGameObjectsWithTag("Enemy");
for(int i=0; i<hitTargets.Length; i++)
{
enemyScripts.Add(hitTargets[i].GetComponent<Collider>(),hitTargets[i].GetComponent<AIDamage>());
}
}
bool firstCollision=true;
void OnCollisionEnter(Collision col)
{
if(firstCollision)
{
firstCollision=false;
Collider[] hitColliders = Physics.OverlapSphere(transform.position, blastRadius);
for(int i=0;i<hitColliders.Length;i++)
{
if(hitColliders[i].CompareTag("Enemy"))
{
enemyScripts[hitColliders[i]].CurrentHealth -= damage;
}
}
}
//explosionEffect
}
}