- Home /
Question by
Klasmic · Jul 23, 2017 at 02:29 PM ·
objectnullreferenceexceptionnull reference exceptionnullreferencenull exception
NullReferenceException: Object reference not set to an instance of an object
I have a script that gives and error on line 18
NullReferenceException: Object reference not set to an instance of an object
but I don't know which object is missing due to lack of clarity.heres my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class treecontroller : MonoBehaviour {
public Vector3 startpos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
startpos = new Vector3 (transform.position.x, transform.position.y - 10);
RaycastHit2D hit2d = Physics2D.Raycast (startpos,Vector2.down);
//this is the dodgy line
gameObject.transform.position = new Vector3(gameObject.transform.position.x, hit2d.collider.gameObject.transform.position.y);
}
}
Comment
@$$anonymous$$lasmic
private Vector3 rawPos;
void Update ()
{
rawPos = new Vector3 (transform.position.x, transform.position.y - 10);
Vector2 tempVector2 = Vector2.down;
RaycastHit2D rc2d = Physics2D.Raycast (rawPos, tempVector2);
}
try this
Best Answer
Answer by Reynarz · Jul 23, 2017 at 03:11 PM
Do this:
if(hit2d.collider != null)
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x,
hit2d.collider.gameObject.transform.position.y);
}
the problem is, "if you are not colliding with a thing, nothing will happen"
Answer by Hellium · Jul 23, 2017 at 03:13 PM
Simply make sure the collider is not null
RaycastHit2D hit2d = Physics2D.Raycast (startpos,Vector2.down);
//this is the dodgy line
if( hit2d.collider != null )
gameObject.transform.position = new Vector3(gameObject.transform.position.x, hit2d.collider.gameObject.transform.position.y);
Your answer
![](https://koobas.hobune.stream/wayback/20220612130933im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
I keep getting a null reference exception, can anyone help? 0 Answers
NullReferenceException: Object reference not set to an instance of an object ? 1 Answer
NullReferenceException: Object reference not set to an instance of an object ProgressBar.Start () 2 Answers
Getting NullReferenceException when setting the rotation of my enemy 1 Answer