Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Refering to an object in front of the player

Discussion in 'Scripting' 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.

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class Attack : MonoBehaviour {
    7. public static int damage = 5;
    8. // Use this for initialization
    9. void Start () {
    10.  
    11. }
    12.  
    13. // Update is called once per frame
    14. void Update () {
    15.  
    16. }
    17.  
    18. void OnTriggerEnter (Collider other){
    19. if(other.gameObject.tag=="Enemy"){
    20. Health.tookdamage=true;
    21. }
    22. }
    23. }
    24.  
    25.  

    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?
     
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    837
    Stop using static and look for the Health component on other.gameObject.
    (other.gameObject.GetComponent<Health>().tookdamage = true)
    You need the Health script to be on the same object as the collider.
     
  3. Deneth

    Deneth

    Joined:
    Jun 26, 2019
    Posts:
    6

    Hell yeah.. Thanks a lot