Im writing some code for a enemy where if you see its face, it will get angry and attack you. Im using a raycast to detect if the player is looking at it, but it isn’t working here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
void FixedUpdate()
{
LayerMask mask = LayerMask.GetMask("SHHEAD");
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, mask)) {
if (hit.collider.gameObject.tag == "SHHEADHIT") {
Debug.DrawRay(transform.position, transform.forward, Color.green);
print("Hit");
}
Debug.Log("Hit!");
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward), Color.green);
}
}
}
Would there be any reason why the debug isn't drawing a line?
Sounds like you wrote a bug… and that means… time to start debugging!
By debugging you can find out exactly what your program is doing so you can fix it.
Use the above techniques to get the information you need in order to reason about what the problem is.
You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
Remember with Unity the code is only a tiny fraction of the problem space. Everything asset- and scene- wise must also be set up correctly to match the associated code and its assumptions.
Pay attention to class names and your typing in general, as you obviously haven’t renamed the above away from its default NewBehaviourScript, so you probably have other typos as well.
Two steps to tutorials and / or example code:
do them perfectly, to the letter (zero typos, including punctuation and capitalization)
stop and understand each step to understand what is going on.
If you go past anything that you don’t understand, then you’re just mimicking what you saw without actually learning, essentially wasting your own time. It’s only two steps. Don’t skip either step.