- Home /
Melee attacking multiple enemies
Hi everyone, i use raycasting for my melee combat, however i am unable to target a new enemy once the first one targeted is destroyed. Basically what i do is create a new gameObject variable when the raycast hits an object which then uses SendMessage to the hit object in order to deal damage Here is my script code:
function Start () {
}
function Update () {
var hit : RaycastHit;
var fwd = transform.TransformDirection(Vector3.forward);
if(Input.GetMouseButtonDown(0)){
if(Physics.Raycast(transform.position, transform.forward,hit, 3)){
if(hit.collider.gameObject.tag == "Enemy"){
var newEnemy = GameObject.FindWithTag("Enemy");
newEnemy.SendMessage("takeDamage", 10);
}
else if (hit.collider.gameObject.tag == "testCol"){
Debug.Log("item hit");
}
}
}
}
Answer by GC1983 · May 07, 2012 at 08:47 PM
If you have multiple enemies tagged "Enemy", it will only assign one. What the engine will do is assign the first tagged enemy and only that enemy. Once you kill it you will have nothing else to be able to hit.
Take "var newEnemy = GameObject.FindWithTag("Enemy");" out of that function and place it in Awake(). This will initialize it once the scene starts; thats all you need. And then alter it to create an array: "var newEnemy : Transform[];" and then change your object locator code to var newEnemy = GameObject.FindGameObjectsWithTag("Enemy"). This will locate every enemy in the scene. And then you use a for loop to search for every enemy within your collider function. This will constantly update your enemy list and should let you hit any of them.
so... I'm here bashing my head on the keyboard figuring out something similar in C#...