- Home /
My Raycast Won't Fire
The raycast is meant to detect something in front of it and if it's an enemy, set it on fire. It worked for about a month but I decided to test everything out today and it decides not to work. I tried using Debug.log to see what was wrong and it just doesn't fire. Everything up to the raycast firing works fine but it refuses to fire.
Here's the part of the script in question:
Vector3 fwd = player.transform.TransformDirection(Vector3.forward);
Debug.Log("fwd Defined");
RaycastHit hit;
Debug.Log("RaycastHit hit was made");
if (Physics.Raycast(transform.position, fwd, out hit))
{
Debug.Log("Raycast Fired And Hit Something");
string tagPlaceholder = hit.collider.gameObject.tag;
Debug.Log("Tag Found");
if (tagPlaceholder == "Enemy")
{
Debug.Log("Is Enemy");
hit.collider.gameObject.GetComponent<Enemy>().onFire = true;
}
}
else if(hit.transform != null)
{
Debug.Log("Hit Nothing");
}
}
}
Answer by SteenPetersen · May 30, 2020 at 05:45 AM
This is tested and working, I think it might be a layers problem so it is always a good idea to include a layermask in your raycasting:
[SerializeField] private LayerMask detectionLayers;
[SerializeField] private float detectionDistance;
GameObject player;
private void Start()
{
player = this.gameObject; // just for my internal testing
Vector3 fwd = player.transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, fwd, out hit, detectionDistance, detectionLayers))
{
if (hit.collider.CompareTag("Enemy"))
{
Debug.Log("Is Enemy");
// make a reference in case we wish to call other methods on the script
Enemy script = hit.collider.gameObject.GetComponent<Enemy>();
script.OnFire = true;
}
}
else/* if (!Physics.Raycast(transform.position, fwd, out hit)) No need for this and 'else' will suffice */
{
Debug.Log("Hit Nothing");
}
}
@SteenPetersen I'm sorry, I edited the question but I guess it didn't go through. I was doing more testing and found out that my else if statement still works if it just doesn't fire. I changed it to only return "Hit Nothing" if it fired and hit nothing and found out that it just didn't fire. Sorry. It should be edited now though.
Your answer
Follow this Question
Related Questions
Finding a certain variable is failing 0 Answers
Line Renderer not showing 0 Answers
Raycast and colliders problem. Corners of two colliders 0 Answers
Physics.Raycast not hit sometimes 0 Answers
Raycast isn't working as expected 1 Answer