NullReferenceException: Object reference not set to an instance of an object
Gun.fireBullet () (at Assets/Scripts/Gun.cs:31)
Here is my all script:
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour {
public GameObject bulletPrefab;
public Transform launchPosition;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0)) {
if (!IsInvoking(“fireBullet”)) {
InvokeRepeating(“fireBullet”, 0f, 0.1f);
}
}
if (Input.GetMouseButtonUp(0)) {
CancelInvoke(“fireBullet”);
}
}
void fireBullet() {
GameObject bullet = Instantiate(bulletPrefab) as GameObject;
I dont know what I am doing wrong? I have Unity version 5.4.2f2.
I tried some Debug.Log and found, that transform.forward is possible and working corectly. But I dont understand differences. Can someone please explain to me and why is in book transform.parent.forward?
The first thing we need to determine if there is a rigidbody attached to the bullet prefab. If there isn’t a Rigidbody component, then that’s the cause of the error.
Make sure to check it that component is present. If that GameObject is still in the Hierarchy, select it and if you see a Rigidbody component in the Inspector, click Apply button.
Next, check your Project Browser and find the original prefab. Click on it, and check the Inspector. If you don’t see a rigidbody component, then that’s your problem. Otherwise, something else may be at play.
I have not Bullet GameObject in Hierarchy. If I take prefab into Hierarchy, GameObject have rigidBody.
I also check SpaceMarine. SpaceMarine-Head and Body have rigidBody but SpaceMarine havent( I checked it with book and it should be correct). Gun script has attached Projectil into Bullet Prefab.
Here is screen:
Hi, this solution worked great for the nullreference error, but the space marine will not stop shooting when i release the mouse button. Do you have any idea what is causing this?