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 nessie2013 · May 08, 2017 at 09:27 AM · declare

why do i get the error Object reference not set to an instance of an object?

when i click play i get this error

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

i am trying to get the score from FoodCollider.cs and use it in GravityScript.cs

FoodCollider.cs

     public float SmallIncrease;
     public float MediumIncrease;
     public float LargeIncrease;
     public float CameraZoom = 0.02f;
     public int Cooldown = 10;
     private float timeStamp;
     public int Mass = 1;
     public int score = 0;
     public string scoreText = "Score: 0";
     public string SpaceDust = "Space Dust";
     public string Asteroid = "Asteroid";
     public string Planet = "Planet";
     public string BlackHole = "BlackHole";
 
     //void Start()
     //{
     //MovementScript ms = GameObject.FindObjectOfType<MovementScript>();
     //}
 
     // void Update()
     // {
     //    if (timeStamp <= Time.time)
     // {
     //  timeStamp = Time.time + Cooldown;
 
     //  transform.localScale -= new Vector3(Increase/ms.Speed, Increase/ms.Speed, Increase/ms.Speed);
     // }
     //}
 
     void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.tag == "SmallFood")
         {
             //if (other.transform.localScale =< transform.localScale)
             // {
 
             //}
             transform.localScale += new Vector3(SmallIncrease, SmallIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 10;
             scoreText = "Score : " + score;
         }
         if (other.gameObject.tag == "MediumFood")
         {
             transform.localScale += new Vector3(MediumIncrease, MediumIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 25;
             scoreText = "Score : " + score;
         }
         if (other.gameObject.tag == "LargeFood")
         {
             transform.localScale += new Vector3(LargeIncrease, LargeIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 60;
             scoreText = "Score : " + score;
         }
        // if (score >= 100)
        // {
           //  GUI.Box(new Rect(20, 10, 100, 20), SpaceDust);
        // }
        // if (score >= 300)
        // {
         //    GUI.Box(new Rect(20, 10, 100, 20), Asteroid);
       //  }
        // if (score >= 2500)
        // {
        //     GUI.Box(new Rect(20, 10, 100, 20), Planet);
       //  }
       //  if (score <= 2500)
       //  {
        //     GUI.Box(new Rect(20, 10, 100, 20), BlackHole);
        // }
 
     }
     void OnGUI()
     {
         GUI.Box(new Rect(10, 10, 100, 20), scoreText);
     }
 }


GravityScript.cs

     private float maxGravDist = 5.0f;
     private GameObject[] planets;
     private float maxGravity = 10.0f;
     private Rigidbody rb;
     FoodColider scoreboard;
     public int score;
 
     void Start()
     {
         rb = GetComponent<Rigidbody>();
         planets = GameObject.FindGameObjectsWithTag("Planet");
         scoreboard = GetComponent<FoodColider>();
     }
 
     void Update()
     {
         score = scoreboard.score;
 
         maxGravDist = 3 * (score / 1000);
     }
 
     void FixedUpdate()
     {
 
         foreach (GameObject planet in planets)
         {
             float dist = Vector3.Distance(planet.transform.position, transform.position);
             if (dist <= maxGravDist)
             {
                 Vector3 v = planet.transform.position - transform.position;
                 rb.AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity);
             }
         }
     }
 }
 

Any help would be appreciated :)

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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by mybluesock · May 08, 2017 at 07:27 PM

You spelled FoodCollider wrong when you initialized the scoreboard.

 scoreboard = GetComponent<FoodColider>();
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 Glurth · May 08, 2017 at 07:54 PM

     rb = GetComponent<Rigidbody>();
      planets = GameObject.FindGameObjectsWithTag("Planet");
      scoreboard = GetComponent<FoodColider>();

It is possible that the gameobject does not have a Rigidbody, or FoodColider component, in which case this function will return null.

But, in your FixedUpdate you used the values, without checking them first. If you attempt to use (access any member of) a reference that is null; you will generate that Null Reference Exception.

So, you should check to ensure that you have a valid object reference, before using it...

e.g.

 if(rb!=null)
 {
   rb.AdForce(...)
 }
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 nessie2013 · May 09, 2017 at 09:01 AM

It is still giving me the error i have looked and everything has a ridgidbody this is my code now.`

@Glurth

 public float maxGravDist = 5.0f;
     private GameObject[] planets;
     public float maxGravity = 10.0f;
     private Rigidbody rb;
     FoodColider scoreboard;
     public int score;
 
     void Start()
     {
         rb = GetComponent<Rigidbody>();
         planets = GameObject.FindGameObjectsWithTag("Planet");
         scoreboard = GetComponent<FoodColider>();
         score = scoreboard.score;
         maxGravDist = 3 * (score / 1000);
 
         if (rb != null)
         {
             Debug.Log("error");
         }
     }
 
     void Update()
     {
         score = scoreboard.score;
 
         maxGravDist = 3 * (score / 1000);
     }
 
     void FixedUpdate()
     {
 
         foreach (GameObject planet in planets)
         {
             float dist = Vector3.Distance(planet.transform.position, transform.position);
             if (dist <= maxGravDist)
             {
                 Vector3 v = planet.transform.position - transform.position;
                 rb.AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity);
             }
         }
     }
 }


  public float SmallIncrease;
     public float MediumIncrease;
     public float LargeIncrease;
     public float CameraZoom = 0.02f;
     public int Cooldown = 10;
     private float timeStamp;
     public int Mass = 1;
     public int score = 1;
     public string scoreText = "Score: 0";
     public string SpaceDust = "Space Dust";
     public string Asteroid = "Asteroid";
     public string Planet = "Planet";
     public string BlackHole = "BlackHole";
 
     //void Start()
     //{
     //MovementScript ms = GameObject.FindObjectOfType<MovementScript>();
     //}
 
     // void Update()
     // {
     //    if (timeStamp <= Time.time)
     // {
     //  timeStamp = Time.time + Cooldown;
 
     //  transform.localScale -= new Vector3(Increase/ms.Speed, Increase/ms.Speed, Increase/ms.Speed);
     // }
     //}
 
 
     void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.tag == "SmallFood")
         {
             //if (other.transform.localScale =< transform.localScale)
             // {
 
             //}
             transform.localScale += new Vector3(SmallIncrease, SmallIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 10;
             scoreText = "Score : " + score;
         }
         if (other.gameObject.tag == "MediumFood")
         {
             transform.localScale += new Vector3(MediumIncrease, MediumIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 25;
             scoreText = "Score : " + score;
         }
         if (other.gameObject.tag == "LargeFood")
         {
             transform.localScale += new Vector3(LargeIncrease, LargeIncrease, CameraZoom);
             Destroy(other.gameObject);
             score += 60;
             scoreText = "Score : " + score;
         }
        // if (score >= 100)
        // {
           //  GUI.Box(new Rect(20, 10, 100, 20), SpaceDust);
        // }
        // if (score >= 300)
        // {
         //    GUI.Box(new Rect(20, 10, 100, 20), Asteroid);
       //  }
        // if (score >= 2500)
        // {
        //     GUI.Box(new Rect(20, 10, 100, 20), Planet);
       //  }
       //  if (score <= 2500)
       //  {
        //     GUI.Box(new Rect(20, 10, 100, 20), BlackHole);
        // }
 
     }
     void OnGUI()
     {
         GUI.Box(new Rect(10, 10, 100, 20), scoreText);
     }
 }
 
Comment
Add comment · Show 3 · 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 Glurth · May 09, 2017 at 06:01 PM 0
Share

you should do that for ALL references. Including "scoreboard" and planets.

avatar image mybluesock · May 09, 2017 at 07:13 PM 0
Share

Also, Collider is still spelled wrong. It should have two l's, not one. Not trying to nitpick, it's just that you've named the script with two l's but refer to it with one.

avatar image Glurth mybluesock · May 09, 2017 at 07:31 PM 0
Share

FoodColider is a custom class, which may be spelled however the programmer wants. But @mybluesock is quite right: the file name should match the class name, exactly, or unity can have problems with it.

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

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

declare script as variable, with variable in it type 1 Answer

Is there a cleaner way to set all the properties when declaring a new object? 2 Answers

Error Initialize array two dimensions C# 0 Answers

A field initializer cannot reference the nonstatic field, method, or property 1 Answer

How to define arrays in shaders? 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