Having weird error. Simple script.

Hey, im having this weird error. I have no idea why, im doing everything good in the inspector, im using particles. Im doing muzzle flash, here’s the script. Thank you for helping:)):face_with_spiral_eyes:

ERROR: NullReferenceException: Object reference not set to an instance of an object

I would suggest you to ignore this

This is the error

using System.Collections;

public class Shootings : MonoBehaviour {

public GameObject bulletPrefab;
public Transform Spawn;
public bool ImFacingLeft;
public Transform muzzelFlash;

void Start ()
{
}

void Update ()
{
if (Input.GetButtonDown(“Fire1”))

{

GameObject muzzle = Instantiate(muzzelFlash, Spawn.position, Spawn.transform.rotation) as GameObject;
muzzle.transform.parent = Spawn.transform;

}

if(Input.GetKeyDown(KeyCode.A))
{
ImFacingLeft = true;
}

if(Input.GetKeyDown(KeyCode.D))
{
ImFacingLeft = false;
}
if (Input.GetButtonDown(“Fire1”))
{
FireBullet();
}

}

void FireBullet(){

//Clone of the bullet
GameObject Clone;

Clone = Instantiate(bulletPrefab, Spawn.position,Spawn.transform.rotation) as GameObject;

if(ImFacingLeft == false)
{
Clone.rigidbody2D.AddForce(Vector2.right * 50);
}

if(ImFacingLeft == true)
{
Clone.rigidbody2D.AddForce(Vector2.right * -50); }
}
}

What is the ‘weird error’?

What error are you getting?

Sorry, forgot to add the error… ;D

ERROR: NullReferenceException: Object reference not set to an instance of an object

Usually it also gives you a line number

Normally when I get the Object Reference error it is because I have not set the Game Object in the inspector for the prefab. What line is the error on?

I did everything good in the Inspector. This is the line that i get the error for:

muzzle.transform.parent = Spawn;

If youre curious on what im doing, my muzzle flash doesnt stay at its parent. When i shoot, i go threw my muzzle flash. Maybe you know how to fix it? Sorry for bad english.

The problem is that muzzleFlash is not a GameObject, so you cannot use

Instantiate(...) as GameObject

instead you should either make muzzleFlash a GameObject

public GameObject muzzleFlash

or change the way you instantiate:

Transform muzzle = Instantiate(...) as Transform;

A link to the answers page containing explanation: Instantiate a GameObjet C# - Questions & Answers - Unity Discussions

Yea i thod its something about the gameObject… Thanks:)