Raycast2D getting errors
I have been trying to create a ray cast to detect the closest enemy and get the distance to that enemy into a variable. I have been trying to get this to work for a while and cant figure out why i still getting errors on my script. I am really new to this and would appreciate if anyone could tell me my mistake.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDistance : MonoBehaviour {
public float enemydistance;
RaycastHit2D hit;
Vector2 raycastdirection;
Vector2 raycastorgin;
LayerMask mask = 1;
// Use this for initialization
void Start () {
raycastorgin = transform.position;
if (gameObject.GetComponent<TeamScript> ().ownertag == "T1") {
raycastdirection = new Vector2 (0f, 1f);
}
if (gameObject.GetComponent<TeamScript> ().ownertag == "T2") {
raycastdirection = new Vector2 (0f, -1f);
}
}
void FixedUpdate () {
Ray2D ray = new Ray2D (transform.position, raycastdirection);
if (Physics2D.Raycast (ray, out hit, Mathf.Infinity)) {
if (hit.collider.gameObject.tag == gameObject.GetComponent<TeamScript> ().enemytag) {
enemydistance = hit.distance;
}
}
Debug.Log (enemydistance);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612172030im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Feild of view only wokring in specific areas of the scene 0 Answers
Inconsistent raycast2D reflecting 0 Answers
Want to do an on-hit effect for a trail renderer in 2D 0 Answers
Raycast on mouse position problem. how not to raycast to 0 1 Answer
Move a Game Object within a radius of another Game Object (2d) 0 Answers