- Home /
Raycast Hit and Raycast by layer
I'm trying to use a Raycast hit to check by tag or name if i'm colliding with other object. I'm cheking layers too and the Raycasthit will be inside this layer hit But I'm getting null reference and I don't know why, I instantiated the Raycast on Start but still getting this problem
Here is my code:
using UnityEngine;
using System.Collections;
public class RiftRay : MonoBehaviour {
public LayerMask mask;
public RaycastHit hit;
public GameObject[] pisos;
public Material[] materiais;
public Color[] anexedColor;
public int distance;
void Start()
{
RaycastHit hit = new RaycastHit();
anexedColor[0] = pisos[0].GetComponent<Renderer>().material.GetColor("_Color");
}
void Update ()
{
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, fwd, Color.green);
if (Physics.Raycast(transform.position, fwd, distance ,mask ) )
{
print("a");
if(hit.transform.gameObject.tag == "Mat1")
{
pisos[0].GetComponent<Renderer>().material.color = Color.black;
}
else if(hit.transform.gameObject.tag != "Mat1")
{
pisos[0].GetComponent<Renderer>().material.color = anexedColor[0];
}
}
}
}
Answer by LaireonGames · Feb 24, 2015 at 08:43 PM
Your using your raycasts the wrong way! Basically RayCastHit is the information returned after a sucessful cast so it makes sense that it has no information since it was not created correctly.
To fix this you need to change your raycast method to something more like this:
if (Physics.Raycast(transform.position, fwd, out hit))
The important part being the out hit which will fill your hit correctly (there will surely be an override to also include your distance and mask)
But that don't solve my problem with layers checker
(there will surely be an override to also include your distance and mask)
If you pass in the mask it will also include your layer checks as ususal. Just hit Ctrl+Space on that method and then keep hitting down until you find with override with all the input you need (include the out RayCastHit)
Your answer
Follow this Question
Related Questions
Opening Door With Raycast 2 Answers
raycast help need 2 Answers
GUI, SpellBar and C#-related questions 1 Answer