cant get raycast to work with tags
I have been trying and trying to get this for awhile now. I worked the first time and then I didn't change anything and the next time I got on it didn't work. So I fixed it again and then no it doesn't work AGAIN. This is the line of code that is the problem
if (Physics.Raycast(transform.position, fwd, hit, RayLength) && hit.collider.tag == "FLEB")
Raylength is an int set to 10
and
var hit : RaycastHit;
var fwd :Vector3 = transform.TransformDirection(Vector3.forward);
Please help me this is driving my crazy.
this is what it says is the error (and yes line 53 matches)
NullReferenceException: Object reference not set to an instance of an object RayCastCollector.FixedUpdate () (at Assets/Scripts/RayCastCollector.js:53)
I think you need to do a second "if" check. So it's like this:
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.forward, out hit, 10))
{
if (hit.collider.tag == "FLEB")
{
do something
}
}
Otherwise you could use a layer mask.
Answer by Downstream · Mar 25, 2016 at 09:29 PM
@uveritegames Well this code works fine for me, and it shows whether I hit anything in the scene view (be sure to change the tag name).
using UnityEngine;
using System.Collections;
public class RayCaster : MonoBehaviour {
public int rayLength = 10;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit RaycastHitInfo;
if (Physics.Raycast (transform.position, transform.forward, out RaycastHitInfo, rayLength) && RaycastHitInfo.collider.gameObject.CompareTag ("RaycastTagFilter")) {
Debug.DrawRay (transform.position, transform.forward * rayLength, Color.green);
} else {
Debug.DrawRay(transform.position, transform.forward * rayLength, Color.red);
}
}
}
And here's the UnityScript version.
#pragma strict
public var rayLength : int;
// Use this for initialization
function Start () {
}
// Update is called once per frame
function Update () {
var RaycastHitInfo : RaycastHit;
if (Physics.Raycast (transform.position, transform.forward, RaycastHitInfo, rayLength) && RaycastHitInfo.collider.gameObject.CompareTag ("RaycastTagFilter")) {
Debug.DrawRay (transform.position, transform.forward * rayLength, Color.green);
} else {
Debug.DrawRay(transform.position, transform.forward * rayLength, Color.red);
}
}
it wont accept RaycastHitInfo, is that defined somewhere else in you code?
I just realized you're using unityscript ins$$anonymous$$d of C#. First line of Update loop.
im not sure how to tell if it worked or not?