• 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
Question by kloo13 · May 13, 2016 at 10:07 AM · animatorbug-perhapsnullreferenceexeption

NullReferenceExeption but everything works great...

Hi, this is my first question so I think I have to introduce myself (you can skip this part from here...): I'm Pascal, I'm new in coding and Unity world (and if you found grammar errors or if I'm using a word for another, my apologies, I do my best to avoid that but I'm French, yep no one is perfect). (... To here)

So, my main Camera has an Animator component with 3 animations: - A new State (I use it as a hub). - "startGame" animation (triggered when a new game start). - "screenShake" animation triggered at some events.

And I have 2 parameters: - Bool screenshake. - Bool startGame.

And my main Camera has a script CameraScript attached to it.

 using UnityEngine;
 using System.Collections;
 
 public class CameraScript : MonoBehaviour 
 {
      public static Animator animator;
     public static int screenShakeHash = Animator.StringToHash("screenShake");
     public static int startGameAnimHash = Animator.StringToHash("startGame");
 
     public static WaitForEndOfFrame wait = new WaitForEndOfFrame();
 
     void Awake()
     {
         animator = GetComponent<Animator>();
     }
 
     public static void Shake(bool enable)
     {
         animator.SetBool(screenShakeHash, enable);
     }
 
     public static IEnumerator ShakeOnce()
     {
         Shake(true);
 
         yield return wait;
 
         Shake(false);
     }
 
     public static void StartGameAnim(bool enable)
     {
         animator.SetBool(startGameAnimHash, enable);
     }
 }

And I have 3 "NullReferenceException: Object reference not set to an instance of an object"...

That did'nt appeared the first time I launched my game.

More info: NullReferenceException: Object reference not set to an instance of an object CameraScript.Shake (Boolean enable) (at Assets/Scripts/CameraScript.cs:19) LaserGameFieldClamper+c__Iterator10.MoveNext () (at Assets/Scripts/LaserGameFieldClamper.cs:72) UnityEngine.MonoBehaviour:StartCoroutine(IEnumerator) LaserGameFieldClamper:OnEnable() (at Assets/Scripts/LaserGameFieldClamper.cs:56) UnityEngine.Object:Instantiate(Object, Vector3, Quaternion) GameManager:ObjectSpawner(GameObject[], GameObject) (at Assets/Scripts/GameManager.cs:340) GameManager:Awake() (at Assets/Scripts/GameManager.cs:73)

And everything works fine... When my game start "startGame" animation is triggered, the two functions, StartGameAnim() and Shake(), do what they have to do and the Coroutine too...

Please Unity comunity, teach me!

Comment

People who like this

0 Show 3
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 rober-psious · May 13, 2016 at 11:03 AM 1
Share

The Awake function is an Unity callback that is called from a GameObject component. Instead of that, your Shake function is a static function that isn't neccessary being called from a component and then it is possible that your "animator" parameter is not initializated when you call to your shake function.

avatar image kloo13 · May 13, 2016 at 01:36 PM 0
Share

Thank you @rober.psious for your answer.

I tried to move to a Start() function, nothing changed, and I put it in an Update() function...

   void Update()
          {
              if(animator == null)
                  animator = GetComponent<Animator>();
          }

and I still have the same issue...

Do you have an idea to suggest? Does my problem comes from my static variables? Is it bad coding practice?

avatar image rober-psious kloo13 · May 13, 2016 at 01:52 PM 1
Share

This has the same problem. Start and Update are callbacks both. This link can help you to understand it.

Can you show the code that calls the Shake function or ShakeOnce coroutine? Maybe someone could help you with this.

1 Reply

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by Glurth · May 13, 2016 at 03:26 PM

This line:

 animator = GetComponent<Animator>();

Does not ENSURE that animator is given a valid (non-null) value. This is because if the object does not contain an Animator component, this function is SUPPOSED to return null.

So, it is imperative that you confirm the value of animator is NOT null, before you use it. e.g.

 public static void Shake(bool enable)
      {
          if(animator!=null)
              animator.SetBool(screenShakeHash, enable);  //the animator and DOT, means we are "using" the variable
          if(animator==null)
                Debug.Log("somethig is wrong, there is no animator attached!");
      }

I see that you check the value in your comments, and reassign it, if null. This is a good idea, but again, for the same reason as above, this does not ENSURE the value is not null.

Comment
Scribe
rober-psious

People who like this

2 Show 9 · 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 rober-psious · May 13, 2016 at 03:35 PM 0
Share

Animator will be never attached because the function is static and no component is associated.

avatar image Glurth rober-psious · May 13, 2016 at 04:09 PM 0
Share

I think your point, @rober.psious is that you cannot call GetComponent from a static function, which is true. To elaborate a little on this (for kloo): A static function does NOT reference any "instance" of the class object. So this means the live object (an "instance"), in the scene, that has components and stuff, is NOT accessible in the static function.
I like to think of static function as functions where "this" is null, with all that implies.

However, in this case, since animator is a static member variable, it CAN be accessed by static functions. (Though this also means ALL instances of this class will refer to the same animator when calling Shake().)

avatar image rober-psious Glurth · May 13, 2016 at 04:12 PM 0
Share

You are right, animator is a static member variable. All you say is true. Sorry ;)

Show more comments
avatar image kloo13 · May 14, 2016 at 09:51 AM 0
Share

Hi! Sorry for my delayed answer. I made some research and tests. That's right, I cannot call GetComponent() from a static function. GetComponent() is a Public function and needs a reference to it to be accessed. And yes, because animator is a static variable it can be accessed by static function. Or else I should have an error "need a reference to access a non-static member".

A static function does NOT reference any "instance" of the class object. So this means the live object (an "instance"), in the scene, that has components and stuff, is NOT accessible in the static function. I like to think of static function as functions where "this" is null, with all that implies.

Could you give me another exemple? I don't get what you mean.

For people reading this post, here are my research links:

  • https://msdn.microsoft.com/fr-fr/library/98f28cdx.aspx

  • https://msdn.microsoft.com/fr-fr/library/79b3xss3.aspx

@Glurth, @rober.psious, thank you for your answers and for your time.

Something strange, error messages "nullReference" no longer appear... and I didn't do anything... any idea about that? (Who I gonna call!? Ghostbugster...) ;)

avatar image Glurth kloo13 · May 14, 2016 at 02:49 PM 0
Share

Perhaps If I use some examples to elaborate, it will help? Internally:

 class SomeClass{
 Int a;
 static int b;
 static public void SFunction()
 {
   a=15; //not a valid command, because It a, is not static.
   this.a=15// same statement, more verbose; also not valid, but it's  little more clear why- it's because "this" is NULL.
  b=15; //perfectly valid
 this.b=15 // NOT valid- because again, in a static function  "this" is null
 }
 
 public void NSfunction()
 {
  a=15; //perfectly valid
  this.a=15; //perfectly valid
 b=15;//perfectly valid- but note: all instances of class will now see this value
 this.b=15;  //NOT valid-  (In my book- though it might actually compile) becuase b does not belong to "this" or any instance, it ONLY belongs to "SomeClass"
 }
 
 }

Externally:

We can access b, without an instance like so:

 SomeClass.b=15
 SomeClass.SFunction();

To access a, we need an instance.

 SomeClass test= new SomeClass(); // NOW we have an instance
 test.a = 15;  // so we can access the non-static values.
 test.NSfunction();
 SomeClass.b=15; //doing this will still be valid, and effect "test" and all other instances.
 SomeClass.SFunction();





avatar image Glurth kloo13 · May 14, 2016 at 03:14 PM 0
Share

Regarding the error disappearing: even if you didn't change the code, if you changed the data it's working with, that could have made the error go away.

Even if you don't check to confirm a particular value is not null, it MIGHT NOT be null.

In general, writing a program when you assume your data is "just so", is much simpler that coding for variable input data (which is usually what you have in real-world applications).

avatar image kloo13 · Jun 06, 2016 at 09:38 PM 0
Share

Hi!

Thank you @Glurth and @rober.psious for your help, it took me some times to understand every answers you gave me (and, for now, some parts keep being "magical" to me). And I met other complications... You know... the learning process...

First idea I had, was to create some public static bools in my CameraScript and use them from other scripts. And, in a coroutine loop, those static bools were tested and used as trigger to call my functions. It worked, but I thought that I could do it better.

Then, after watching a tuto about player data and serialization here at 13'30 Mike Geig puts its script in a public static variable that hold a reference to its class

edit: @Glurth, I think that your explanations helped me to understand what Mike Geig was doing.

So I made this:

 public class CameraScript : MonoBehaviour 
 {
     public static CameraScript camScript;
 
     public Animator animator;
     private int screenShakeHash = Animator.StringToHash("screenShake");
     private int startGameAnimHash = Animator.StringToHash("startGame");
 
     void Awake()
     {
         camScript = GetComponent<CameraScript>();
         animator = GetComponent<Animator>();
     }
 
     public void Shake(bool enable)
     { 
         animator.SetBool(screenShakeHash, enable);
     }
 
     public IEnumerator ShakeOnce()
     {
         animator.SetBool(screenShakeHash, true);
 
         yield return GameManager.wfs_dotOneSec;
 
         animator.SetBool(screenShakeHash, false);
     }
 
     public void StartGameAnim()
     {
         animator.SetTrigger(startGameAnimHash);
     }
 }

But my build stopped working because of a nullReferenceExeption. This error was happening at launch then in game every things worked just fine... I was back to the same situation as my first post. So in my other classes that was calling my functions by this reference I put this:

 if(CameraScript.camScript != null)
     {
         CameraScript.camScript.MyFunction();
     }

And everything work fine. No error at launch, and in game, every thing work like a charm! Is it bad coding practice? Do you have any advice for me, or maybe another solution?

avatar image Glurth kloo13 · Jun 07, 2016 at 03:06 AM 0
Share

checking a value for null, before you use it is a GOOD coding practice. I'm sorry that it was not clear this is exactly what I was recommending when I said that you could not be SURE a particular value is not null (so, you need to check).

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

57 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

Related Questions

Delay when activating gameobject and calling Animator.Play() at the same time 0 Answers

Help with 8-DOM Weapon Sprite Issue 0 Answers

Rigidbody / Animator Moving Y Position - bug? 1 Answer

AvatarBuilder.BuildHumanAvatar set NaN positions with some avatars 1 Answer

Animator not initialized "cautions" 0 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