- Home /
destroy gameobject with ray
hey,
I am trying make a scipt to destroy gameobject which is hit by ray that I am casting. Ray casting is working good, but when it hits gameobject it makes this error:
NullReferenceException: Object reference not set to an instance of an object Movement.Update () (at Assets/Scripts/Movement.js:13)
I cant figure it out. #pragma strict
var fwd;
var hit : RaycastHit;
function Update () {
if(Input.GetKey("s")){
fwd = transform.TransformDirection (-Vector3.up);
Debug.DrawRay(transform.position, fwd, Color.green);
if (Physics.Raycast (transform.position, fwd, 10)) {
Destroy(hit.collider.gameObject);
}
}
}
Answer by KellyThomas · Dec 26, 2013 at 03:55 PM
This error is telling you that hit
has no value assigned to it. This is because you never assign a value to it.
There is an overload of Physics.Raycast()
with the following signature:
static function Raycast(origin: Vector3, direction: Vector3, hitInfo: RaycastHit, distance: float = Mathf.Infinity, layerMask: int = DefaultRaycastLayers): bool;
You can use it by making the following change:
// if (Physics.Raycast (transform.position, fwd, 10)) {
if (Physics.Raycast (transform.position, fwd, hit, 10)) {
After making this change you will be passing hit
into the Raycast()
function where it will be populated with information about the RaycastHit
(if one occurs).
Your answer
![](https://koobas.hobune.stream/wayback/20220613124911im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast won't work after Camera transforms position. Please help! 1 Answer
Destroying gameobject 2 Answers
how to hit a gui button with raycast 2 Answers
[SOLVED] Raycast for custom button JS 1 Answer
Raycasting is not working! 2 Answers