Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by RobbyT15 · Dec 23, 2015 at 10:46 AM · c#unity 5nullreferenceexception

Why is my component coming back as null?

I'm trying to update a variable from one script in another and was initially getting the error

 NullReferenceException: Object reference not set to an instance of an object GameController+<asteroidWaves>c__Iterator2.MoveNext () (at Assets/Scripts/GameController.cs:51)

Line 51 is asteroid.increaseSpeed(speed);

When I did a check to make sure that it is indeed null, I'm being told that it is. Why am I returning null on AsteroidMover and how do I fix it?

 public class GameController:MonoBehaviour{
     public GameObject hazard;
     public Vector3 hazard_values;
     public int min_asteroids;
     public int max_asteroids;
     private int hazard_count;
     public float spawn_wait;
     public float start_wait;
     public float wave_wait;
     private int wave_count = 0;
     public Text score_text;
     private int score;
     public Text restart;
     public Text game_over_text;
     private bool game_over;
     private bool new_game;
     private AsteroidMover asteroid;
 
     void Start(){
         game_over = false;
         new_game = false;
         restart.text = "";
         game_over_text.text = "";
         score = 0;
         updateScore();
         StartCoroutine(asteroidWaves());
     }
 
     void Update(){
         if(new_game){
             if(Input.GetKeyDown(KeyCode.Return)){
                 Application.LoadLevel(Application.loadedLevel);
             }
         }
     }
     
     IEnumerator asteroidWaves(){
         yield return new WaitForSeconds(start_wait);
         while(true){
             asteroid = GetComponent<AsteroidMover>();
             wave_count += 1;
             if(asteroid != null){
                 if(wave_count > 1){
                     min_asteroids *= wave_count;
                     max_asteroids += min_asteroids;
                     asteroid.increaseSpeed();
                 }
             }
             else{
                 Debug.Log ("Asteroid is null");
             }
 
             hazard_count = Random.Range(min_asteroids, max_asteroids);
             for(int i = 0; i < hazard_count; i++){
                 Vector3 hazard_position = new Vector3(Random.Range(-hazard_values.x, hazard_values.x), hazard_values.y, hazard_values.z);
                 Quaternion hazard_rotation = Quaternion.identity;
                 Instantiate(hazard, hazard_position, hazard_rotation);
                 yield return new WaitForSeconds(spawn_wait);
             }
             yield return new WaitForSeconds(wave_wait);
         }
     }
 }
         
         public class AsteroidMover:MonoBehaviour{
             private Rigidbody asteroid;
             public float speed;
             
             void Start(){
                 asteroid = GetComponent<Rigidbody>();
                 asteroid.velocity = transform.forward * speed;
             }
         
             public void increaseSpeed(){
                 speed += 0.5f;
                 Debug.Log (speed);
             }
         }





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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by wibble82 · Dec 23, 2015 at 10:54 AM

I suspect it is because you only set 'asteroid' in the Start function of GameController, however your logic is:

  if(asteroid != null)
  {
        asteroid = FindObjectOfType<AsteroidMover> ();
  }

So that says "if my asteroid is not null, find an asteroid"

So if your asteroid is already null, you will never attempt to find an asteroid.

Presumably that's a typo, and should read:

      if(asteroid == null)
      {
            asteroid = FindObjectOfType<AsteroidMover> ();
      }
 

Although unless you intend to set 'asteroid' in the inspector, the 'if statement' is probably redundant, as you always want to find your asteroid in the Start function, so it could probably just be:

 asteroid = FindObjectOfType<AsteroidMover> ();

Hope that helps

-Chris

Comment
Add comment · Show 7 · 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 RobbyT15 · Dec 23, 2015 at 11:34 AM 0
Share

Ok, so if I just get rid of the if statement, asteroid should never return null?

avatar image wibble82 RobbyT15 · Dec 23, 2015 at 11:36 AM 0
Share

Assu$$anonymous$$g there is an object in the world with an 'Asteroid$$anonymous$$over' component attached to it, yes!

If you don't have an 'Asteroid$$anonymous$$over' in your scene, then it won't find one.

Give it a try :)

-Chris

avatar image RobbyT15 wibble82 · Dec 23, 2015 at 11:46 AM 0
Share

I have the Asteroid$$anonymous$$over script attached to a prefab that gets instantiated when the game starts.

Show more comments
avatar image wibble82 · Dec 23, 2015 at 12:08 PM 1
Share

No problem - we all have to learn :)

FindObjectOfType simply searches the scene for a GameObject that contains a component of type Asteroid$$anonymous$$over.

If one doesn't exist, it will return null.

If you are waiting until the game actually runs before Instantiating them, then you would need to make sure you didn't look for it until they had been instantiated. I don't know enough about your code to know if that'll be the case, but if GameController exists when the scene starts up, then you'll be relying on the asteroids being instantiated before 'Start' is called on it, which is probably optimisitic.

You could try fiddling with script priorities, but the simplest approach is probably just to find it when you need it:

     IEnumerator asteroidWaves()
     {
         yield return new WaitForSeconds(start_wait);
         while(true)
         {
             wave_count += 1;
 
             //just locally find our asteroid here before we use it
             //NOTE: we can now get rid of the member variable called 'asteroid'
             Asteroid$$anonymous$$over asteroid = FindObjectOfType<Asteroid$$anonymous$$over> ();
             if(asteroid != null)
             {
                 if(wave_count > 1)
                 {
                     $$anonymous$$_asteroids *= wave_count;
                     max_asteroids += $$anonymous$$_asteroids;
                     asteroid.increaseSpeed(speed);
                 }
             }   
      
             hazard_count = Random.Range($$anonymous$$_asteroids, max_asteroids);
             for(int i = 0; i < hazard_count; i++)
             {
                 Vector3 hazard_position = new Vector3(Random.Range(-hazard_values.x, hazard_values.x), hazard_values.y, hazard_values.z);
                 Quaternion hazard_rotation = Quaternion.identity;
                 Instantiate(hazard, hazard_position, hazard_rotation);
                 yield return new WaitForSeconds(spawn_wait);
             }
 
             yield return new WaitForSeconds(wave_wait);
 
             if(game_over)
             {
                 restart.text = "Press 'Enter' to start a new game.";
                 new_game = true;
                 break;
             }
         }
     }

avatar image RobbyT15 wibble82 · Dec 23, 2015 at 08:03 PM 1
Share

So, I implemented this and asteroid is still returning as null.

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

52 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 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 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

Controller gives NullReferenceException and Teleporter is unresponsive when collided 1 Answer

Problem referencing an int inside of a dictionary. 0 Answers

Varialbes on prefab script always null 0 Answers

NullRefrenceException - Cant find the cost 1 Answer

NullReferenceException: Object reference not set to an instance of an object, again 2 Answers


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