- Home /
[js]NullReferenceException: Object reference not set to an instance of an object
This is my script:
#pragma strict
var woodPlank : GameObject;
var Player : Transform;
var maxDist : float;
private var InventScript : Inventory;
function Start()
{
InventScript = GameObject.Find("Player").GetComponent(Inventory);
}
function Update ()
{
var hit : RaycastHit;
if (Input.GetButtonDown("Fire2") && hit.transform.tag == "PlaceableAreas")
{
if ((InventScript.woodAmount - 1) >= 0)
{
if (Physics.Raycast(transform.position, transform.forward, hit, maxDist))
{
var instantiatedPlank = Instantiate(woodPlank, hit.point, Player.rotation);
instantiatedPlank.transform.position.y += 1;
InventScript.woodAmount -= 1;
}
}
}
}
There is absolutely nothing wrong with this script, but apparently there's something wrong with hit.transform.tag == "PlaceableAreas"
even though the syntax is right, and there is a transform (the terrain) which has the tag PlaceableAreas, and it's spelled right, it gives me NullReferenceException: Object reference not set to an instance of an object. Why is this?
Answer by akauper · Apr 15, 2014 at 09:08 PM
You say there is nothing wrong with the script. Yet clearly there is since your getting an error =P
Currently you are declaring hit, then attempting to check if hit.transform.tag == "PlaceableAreas" when you click "Fire2". But hit hasnt been assigned yet! You need to do your raycast before you can check what the raycast hit.
Heres updated code to reflect this:
#pragma strict
var woodPlank : GameObject;
var Player : Transform;
var maxDist : float;
private var InventScript : Inventory;
function Start()
{
InventScript = GameObject.Find("Player").GetComponent(Inventory);
}
function Update()
{
var hit : RaycastHit;
if(Input.GetButtonDown("Fire2"))
{
if(Physics.Raycast(transform.position, transform.forward, hit, maxDist))
{
if(hit && hit.transform.tag == "PlaceableAreas" && (InventScript.woodAmount - 1) >= 0)
{
var instantiatedPlank = Instantiate(woodPlank, hit.point, Player.rotation);
instantiatedPlank.transform.position.y += 1;
InventScript.woodAmount -= 1;
}
}
}
}
No problem. If the answer helped you mark it as the correct answer so people searching in the future can find the answer to their question more easily :)
Also, if you need any more help don't hesitate to P$$anonymous$$ me. I'm happy to help.
Your answer
Follow this Question
Related Questions
NullReferenceException 1 Answer
Hi I get an error code when i'm using my Javascript and I can't understand how to fix it... :( 1 Answer
Object reference not set to an instance of an object 1 Answer
Remmember the spawner 2 Answers
NullReferenceException: Object reference not set to an instance of an object 1 Answer