Search Unity

How to Refer to the enemy infront of me and not to some random Enemy

Discussion in 'Prefabs' started by Deneth, Aug 7, 2019.

  1. Deneth

    Deneth

    Joined:
    Jun 26, 2019
    Posts:
    6
    I am new to unity and when i attack an enemy, some random enemy on the scene gets damaged.

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

    public class Attack : MonoBehaviour {
    public static int damage = 5;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    void OnTriggerEnter (Collider other){
    if(other.gameObject.tag=="Enemy"){
    Health.tookdamage=true;
    }
    }
    }

    when i check for the gameobject with the tag enemy, how can I refer to the one infront of me?
    I have attached a script named Health and in it there is a global bool took damage. But took damage becomes true on some other enemy. How can I specify the Health Script of the enemy i hit now?
     
    Last edited: Aug 7, 2019
  2. Couple of things.

    Please, select the forum where you open a new thread carefully. Your question isn't related to Prefabs, so your question is in the wrong place. You can select for example the Scripting forum:
    https://forum.unity.com/forums/scripting.12/

    Next thing is whenever you post code for us to help you with your problem, please, have the courtesy to use code tags so we can read your code more easier. Here you can learn how to do it:
    https://forum.unity.com/threads/using-code-tags-properly.143875/

    Now, about your problem.
    Obviously you are using a trigger which is bigger than your player and possibly extends in more directions.
    Possible solutions:
    - change the size and orientation of the trigger to only extend into the direction you want and then you can have only a couple of enemies to take care of
    - you can fire a Ray in the direction of the player and choose the closest one to operate on (you may need more than one Ray when you have slim enemies so you take care of a slice of the direction your player facing), also you need to think about the height of the enemies as well
    - this solution is the most work but the most precise as well, you collect the enemies in the trigger zone in a list or array, go through this array/list and you calculate the distance to the player and the direction (vector) from the player. You select the closest enemy, in somewhat front of the player
     
  3. Deneth

    Deneth

    Joined:
    Jun 26, 2019
    Posts:
    6

    Sorry, for the inconvenience happened cause I didn't see where I am posting this thing. Any way Thanks for the help.
     
    Lurking-Ninja likes this.