Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
8
Question by dexterNIC · Jul 03, 2013 at 12:12 PM · c#nullreferenceexceptioneventloadleveldelegate

Reloading Scene causes "null" object references.

I am creating a prototype for a game, wherein there is character say "baby superman" who is flying and on the path he would get power-ups like booster rockets, which would eventually increase his speed and fly faster. I am using C#.

Here I have used delegates & events, where OnCollisionEnter on the power up will fire up an event AddBoosterRockets and as "superbaby" has it its function attached to this event, which would show the rocket animation and the speedup. This is working fine as many times I click the play button, start/stop/restart it, there is no issues in the execution.

Now OnGUI function, I have added a "Reset" button which when clicked will load the current level i.e. via "Application.loadedLevel(0)". The superbaby moves as intended and as soon as it hits the power up, event is received and when I attach the rocket animation as the child of superbaby gameObject, I need to assign the transform of superbaby as the parent of the rocket animation, this where where I start getting the following error : The transform is "null", I have no clue how this happens.

The object of type 'C_SuperBaby' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

This error only occurs when I reload the via "Application.loadedLevel(0)". This never occurs when I click the play button on the top and restart as many times I want. I did google and more frequently the topic in discussion came was - to remove any static variables from the code to avoid loosing of the reference, to avoid null reference.

I don't know whether this error is caused by the static key word used in front of the declaration of the event. i.e.

public delegate void delegateAddBoosterRockets();
public static event delegateAddBoosterRockets AddBoosterRockets;

There are no other static keyword used other than for declaring events. I would love to use delegate & events, and I believe there might be some way to overcome this issue. Could anyone kindly guide me at this front?

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
9
Best Answer

Answer by Slobdell · Jul 03, 2013 at 11:42 PM

It's because super baby is created on application load, and I would guess whatever is accessing super baby is not destroyed when you load the level. So when you load the level, a NEW super baby is created but whatever was accessing super baby still have a reference to the old super baby. Each time you load the level you just need to make sure everything has updated references.

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
24

Answer by dexterNIC · Jul 04, 2013 at 05:53 AM

Thank you Slobdell, thank you for pointing in right direction.

After few hours of searching on google, unity answers, eventually was on this page of StackOverflow

  1. unity-missingreferenceexception-when-loading-same-scene-for-second-time

where the very first answer explains static variables as "Static variables on the other hand are not destroyed because they are part of a class, not an instance. You have to reset these manually.**" So it was pretty clear that what all you assign to a static variable must be monitored mannually.

So this meant the static event variable being a part of class still hold the referce of the eventhandlers of C_SuperBaby within the AddBooosterRockets event of C_PowerUps class. As we use Class.EventName += EventHandler to add a listener, similarly we can remove the listener by Class.EventName -= EventHandler . Now when should we remove the listeners, for this please refere the order of execution of methods or processes Unity.

  1. Execution Order

  2. OnDestroy

There you can see the OnDestroy is fired when a MonoBehaviour object is destroyed. This is what I was looking for, so added the following lines of code inside C_SuperBaby at the end.

 // Whenever the object gets destroyed.
 void OnDestroy(){
      C_PowerUps.AddBoosterRockets -= AddBoosterRocketsHandler;
 }
 

where AddBoosterRocketsHandler is method from C_SuperBaby, and yes thats pretty much of it. Just make sure whenever you are using statics variables and assigning them reference do make sure to monitor them as well.

I hope this will help others too... :)

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 nipundavid · Mar 31, 2016 at 08:12 PM 2
Share

You have no idea how helpful this was... Thanks

avatar image Keepps65 · Nov 30, 2020 at 01:32 PM 1
Share

This saved me, thanks! I was reloading a scene and getting null refs. I then unsubscribed from the event that I was using and problem solved!

avatar image de_Lich · Aug 23, 2021 at 06:31 PM 0
Share

Thank you so much! I have been looking for that solution for almost month!

avatar image
2

Answer by satanas · Sep 20, 2017 at 05:11 AM

Instead of using OnDestroy, I prefer to use OnEnable and OnDisable as a good practice to subscribe and unsubscribe methods to an event; following the suggestions on the tutorial in the official documentation. If you subscribe to an event but don't unsubscribe, you'll have memory leaks and weird behaviors in your code.

So, let's say you have the event OnMyEvent defined in the class MyClass and you want to subscribe using the method MyMethod. In order to avoid the situation pointed out above, just do as follows:

 void OnEnable() {
     // Subscribe to the event
     MyClass.OnMyEvent += MyMethod;
 }
 
 void OnDisable() {
     // Unsubscribe to the event
     MyClass.OnMyEvent -= MyMethod;
 }

OnEnable and OnDisable also guarantee that the subscription is handled properly when the game enters other states as paused or unpaused, so should be the preferred way to go.

Hope it helps.

Comment
Add comment · Show 1 · 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

22 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

Related Questions

Event to change level 1 Answer

Parametrize generic event system (DRY it) 1 Answer

C# event setup, no result 0 Answers

Sharing delegate types across scripts 1 Answer

Multiple Cars not working 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