- Home /
Object reference not set to an instance of an object
Hi, so I have a script that makes it so that the hands attached to the gun model are not visible when you are not holding it. I have both variables assigned but when I run the game I get the runtime error shown above. Here is my script.
var walkScript: PlayerMovementScript;
var parentGun: GameObject;
function Start ()
{
walkScript = GameObject.FindWithTag("Player").GetComponent(PlayerMovementScript);
}
function Update ()
{
if(walkScript.currentGun == parentGun)
{
gameObject.GetComponent(MeshRenderer).enabled = true;
}
if(walkScript.currentGun != parentGun)
{
gameObject.GetComponent(MeshRenderer).enabled = false;
}
}
Thanks!
There are many places where something could be null (aka Object reference not set...) in that code. Which line is causing it?
Listing the line the error occurred on (better yet commenting the line), is helpful in getting an accurate answer. At the end of Start(), put:
if (walkScript == null)
Debug.Log("Null walkScript");
If it is null, check to make sure your player game object is tagged with "Player", not just named "Player".
I get the error when the gameObject.GetComponent($$anonymous$$eshRenderer).enabled = false; runs
If that's the line, then the object has no $$anonymous$$eshRenderer component and thus that returns null and thus .enabled on null goes boom.
Oh, wow. I didn't even notice it was Skinned$$anonymous$$eshRenderer. However, I still get an error from those same lines. If it helps, here is a screen. http://puu.sh/2iIVf
Answer by dendens2 · Mar 16, 2013 at 06:17 PM
Ok guys, figured it out. One of the hands was SkinnedMeshRenderer, the other was MeshRenderer, since it was not animated. Fixed it with this:
var walkScript: PlayerMovementScript;
var parentGun: GameObject;
function Start ()
{
walkScript = GameObject.FindWithTag("Player").GetComponent(PlayerMovementScript);
}
function Update ()
{
if(walkScript.currentGun == parentGun)
{
if(gameObject.GetComponent(SkinnedMeshRenderer))
{
gameObject.GetComponent(SkinnedMeshRenderer).enabled = true;
}
else
{
gameObject.GetComponent(MeshRenderer).enabled = true;
}
}
if(walkScript.currentGun != parentGun)
{
if(gameObject.GetComponent(SkinnedMeshRenderer))
{
gameObject.GetComponent(SkinnedMeshRenderer).enabled = false;
}
else
{
gameObject.GetComponent(MeshRenderer).enabled = false;
}
}
}
Thanks guys!