Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by liwuen · Nov 27, 2013 at 09:22 AM · instantiateobjectnullreferenceexceptioninstancebullets

NullReference Exception when adding a class

Hello everyone. I'm developing a shooting game with different types of bullets (pressing 1, 2, 3 and 4 will change them). I have a BasicBullet.cs which is like this

 using UnityEngine;
 using System.Collections;
 
 public class BasicBullet : MonoBehaviour
 {
     public float speed = 5.0f;
     public float DestroyTime = 10.0f;
     public Vector3 velocity;
     
     public void changeVelocity(Vector3 v)
     {
         velocity = v;
     }
 
     void Start ()
     {
         Destroy (gameObject, DestroyTime);
     }
 
 
     void FixedUpdate ()
     {
         // TO DO
         transform.position += velocity * Time.deltaTime;
     }
     
 }

And my second bullet is like this using UnityEngine; using System.Collections;

 public class Bullet2 : MonoBehaviour {
 
     public float speed = 5.0f;
     public float DestroyTime = 10.0f;
     public Vector3 velocity;
     
     public void changeVelocity(Vector3 v)
     {
         velocity = v;
     }
     
     void Start ()
     {
         Destroy (gameObject, DestroyTime);
     }
     
     
     void FixedUpdate ()
     {
         // TO DO
         transform.position += velocity * Time.deltaTime;
     }
 }

which basically are the same, just for tests purposes. Now, in my player shooting part, this is the code that I have

 using UnityEngine;
 using System.Collections;
 
 public class Shoot : MonoBehaviour
 {
     public AudioClip shootAudio;
     private AudioSource audioSource;
     public GameObject bulletPrefab;
     public GameObject fireParticle;
     public float fireRate = 0.1f;
     
     private float nextFire = 0.0f;
     private bool shooting = false;
     private int gunMode = 1;
     
     void Start()
     {
         audioSource = GetComponent<AudioSource>();
         
     }
 
     // Update is called once per frame
     void Update ()
     {
         //use mouse to fire
         if (Input.GetButtonDown ("Fire1"))
             shooting = true;
         if (Input.GetButtonUp ("Fire1"))
             shooting = false;
         
         //use keyboard to change gun type
         if (Input.GetKey("1"))
             gunMode = 1;
         else if(Input.GetKey("2"))
             gunMode = 2;
         else if(Input.GetKey("3"))
             gunMode = 3;
         else if(Input.GetKey("4"))
             gunMode = 4;
         
         if (shooting)
         {
             if(gunMode == 1  && Time.time > nextFire)
             {
                 fireParticle.SetActive(false);
                 audioSource.PlayOneShot(shootAudio);
                 GameObject bullet = (GameObject)Instantiate(bulletPrefab,this.transform.position + this.transform.forward + this.transform.up, Quaternion.identity);
                 
                 BasicBullet bulletComp = bullet.GetComponent<BasicBullet>();
                 bulletComp.changeVelocity(this.transform.forward * 10f);
                 nextFire = Time.time + fireRate;
             }
             else if(gunMode == 2)
             {
                 fireParticle.SetActive(true);
             }
             //TO DO
             else if(gunMode == 3 && Time.time > nextFire)
             {
                 fireParticle.SetActive(false);
                 audioSource.PlayOneShot(shootAudio);
                 GameObject bullet = (GameObject)Instantiate(bulletPrefab,this.transform.position + this.transform.forward + this.transform.up, Quaternion.identity);
                 
                 Bullet2 bulletComp = bullet.GetComponent<Bullet2>(); //<----PROBLEM!!!
                 bulletComp.changeVelocity(this.transform.forward * 10f);
                 nextFire = Time.time + fireRate;
             }
             else if(gunMode == 4)
             {
                 
             }
         }
         else
         {
             if(gunMode == 2)
             {
                 fireParticle.SetActive(false);
             }
         }
     }
     
     void OnTriggerStay(Collider other)
     {
         //for Flamethrower
         if(gunMode == 2)
         {
             if (other.attachedRigidbody)
             other.attachedRigidbody.AddForce(this.transform.forward * 50f);
         }
     }
 }
 

but I get a NullReferenceException in here

 Bullet2 bulletComp = bullet.GetComponent<Bullet2>();
                 bulletComp.changeVelocity(this.transform.forward * 10f);
                 nextFire = Time.time + fireRate;

What is the problem? Can anyone help me? Thanks! The error is this one:

 NullReferenceException: Object reference not set to an instance of an object
 Shoot.Update () (at Assets/Scripts/Player/Shoot.cs:65)

 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by raimon.massanet · Nov 27, 2013 at 09:34 AM

You are instantiating the same prefab (`bulletPrefab`) in both cases. Is that intended behavior? If the prefab does not contain a Bullet2 script, GetComponent will return null, and you will get a NullReferenceException.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Komak57 · Nov 27, 2013 at 10:48 AM

It looks like you're trying to create a bullet object, but grabbing a component script. Bad form. First, generate a GameObject called BulletA, and attach Bullet1 to it. Next, generate a GameObject called BulletB, and attach Bullet2 to it. Drag them to your prefabs folder and delete it from your scene. Next, add a public GameObject bullet; to your Shoot script. This will allow you to drag-and-drop your BulletA or BulletB prefab as the designated item. In the case you want to spawn both bullets, create 2 public GameObject bullet_a, bullet_b; handles. Now, when you've decided this object should spawn, do something like this:

 GameObject bullet = (GameObject) GameObject.Instantiate(bullet_a, transform.position, transform.forward);

That's a temporary handle to a freshly spawned copy of bullet_a summoned at the parent scripts position, pointing forward in the parents direction.

From here, you can either throw the bullet by initial velocity, or raycast-teleport inside the Bullet1 script. Remember to destroy the bullet (preferably within it's script) when it is deemed obsolete (out of game bound, collided, traveled for X seconds or meters).

This guy will get you going with tutorials and visual aids: ETeeskiTutorials(Youtube)

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to instantiate object onto other object from script 1 Answer

The infamous: Object Reference not set to an instance of an object 1 Answer

Instantiate a COMPLETELY Unique Instance of an Object 1 Answer

" NullReferenceException: Object reference not set to an instance of an object" 3 Answers

NullReferenceException Error 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges