Object.layer = nullreference

So…
I’ve been trying to change the layer of an object for a while now, searched a bit, tried some stuff, but I cant figure it out why its not working.

                    if(owner.tag == "Player"){
                        GameObject bolt_ = Instantiate(bolt, curMuzzle.position, curMuzzle.rotation) as GameObject;
                        bolt_.layer = LayerMask.NameToLayer("Player_Projectiles");
                        bolt_.tag = "Player_Projectile";
                        
                    }

Unity is pointing the problem on this line:

 bolt_.layer = LayerMask.NameToLayer("Player_Projectiles");

I tried to set the layer directly as an int but got the same problem.

this is what Unity log says:

NullReferenceException: Object reference not set to an instance of an object
Weapon.Shoot (UnityEngine.GameObject owner) (at Assets/GameData/Scripts/Weapon/Weapon.cs:75)
_Player_Controller.InputManager () (at Assets/GameData/Scripts/Player/_Player_Controller.cs:35)
_Player_Controller.Update () (at Assets/GameData/Scripts/Player/_Player_Controller.cs:27)

full code:
http://pastebin.com/NxB03rWi

I’m sorry if a problem like this has been solved already on another thread and thanks in advance for your help.

Well your problem is the combination of 3 things:

  • Your perfab variable type is “Projectiles” so the instantiated object is of type “Projectiles”
  • You use an as-cast to GameObject which will of course fail since the type “Projectiles” can’t be casted to GameObject
  • Since an as-cast simply returns “null” when the cast fails you get a null reference exception as soon as you try to use your reference.

Since your variable is declared as

public Projectiles bolt;

your Instantiate line should look like this:

Projectiles bolt_ = (Projectiles)Instantiate(bolt, curMuzzle.position, curMuzzle.rotation);
bolt_.gameObject.layer = LayerMask.NameToLayer("Player_Projectiles");
bolt_.gameObject.tag = "Player_Projectile";