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 /
avatar image
1
Question by elenzil · Apr 08, 2016 at 11:34 PM · nulldelegatecallback

Delegate.Target null-check fails when it's actually null and also prints as null.

I tried to make my example as concise as possible, but it's still a little long. Apologies.

I have a standard delegate pattern, but sometimes the class instance the delegate belongs to may have been destroyed when i go to call the delegate. So, i check myDelegate.Target == null, but the check always evaluates an not-equal. But if the delegate itself prints out the value of this, the result is "null". So, i started checking if myDelegate.Target.ToString() is the string "null", and that check behaves as expected. What am i missing here ? Is this a C# weirdness or a Unity weirdness ?

Here's a script demonstrating the issue.

 using UnityEngine;
 using System.Collections;
 
 // The console output of this program is this:
 //
 // nullMethod1: False nullMethod2: False
 // Calling in method 1
 // You called me! this = New Game Object (LittleGuy)
 // Calling in method 2
 // You called me! this = New Game Object (LittleGuy)
 // doing careful delegate callback after the GameObject the delegate belonged to has been destroyed..
 // nullMethod1: False nullMethod2: True
 // Calling in method 1
 // You called me! this = null
 
 public class LittleGuy : MonoBehaviour {
   public void callMe() {
     Debug.Log("You called me! this = " + this.ToString());
   }
 }
 
 public class delegateTargetTest : MonoBehaviour {
 
   public delegate void SimpleDelegate();
 
   public SimpleDelegate myDelegate;
 
   public void Start() {
 
     GameObject go = new GameObject();
     LittleGuy lg = go.AddComponent<LittleGuy>();
     StartCoroutine(beginTest(lg.callMe));
 
     GameObject.Destroy(go);
   }
 
   private IEnumerator beginTest(SimpleDelegate dtt) {
     Debug.Log("doing careful delegate callback while everything is fine..");
     tryCallDelegate(dtt);
 
     // give the GameObject time to be destroyed.
     yield return new WaitForSeconds(0.5f);
 
     Debug.Log("doing careful delegate callback after the GameObject the delegate belonged to has been destroyed..");
     tryCallDelegate(dtt);
   }
 
   void tryCallDelegate(SimpleDelegate dtt) {
     bool nullTestMethod1 = (dtt.Target == null);
     bool nullTestMethod2 = string.Equals(dtt.Target.ToString(), "null");
     Debug.Log("nullMethod1: " + nullTestMethod1 + " nullMethod2: " + nullTestMethod2);
 
     if (!nullTestMethod1) {
       Debug.Log("Calling in method 1");
       dtt();
     }
 
     if (!nullTestMethod2) {
       Debug.Log("Calling in method 2");
       dtt();
     }
   }
 }

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

Answer by Bunny83 · Apr 09, 2016 at 04:47 AM

As you might know in the C# world it's impossible to actually destroy any objects. Class instances are actually destroyed by the garbage collector once all references to the instance are gone. However all classes derived from UnityEngine.Object can be destroyed since they have a C++ counterpart in the engines core.

The managed "part" of those objects can't be destroyed. References in the managed world are always valid unless they are actually null. Unity implemented a custom == operator for the UnityEngine.Object class which when comparing the instance to null will check if the object has been destroyed and return "true", even the (managed) object is still there. They also implemented a custom Equals method which also returns "true" when comparing to null.

This works pretty well as long as you work with variable of type UnityEngine.Object or any derived type (like GameObject, Component, MonoBehaviour, ...). However if you cast such a reference to System.Object the custom == operator isn't used so a null check will return false since the actual managed object is still there.

If you want to do a null check of a System.Object reference and include Unity's fake-null-objects you can do this:

 object obj;
 
 if (obj == null)
     return; // the reference actually is null --> early exit
 if ((obj is UnityEngine.Object) && (obj.Equals(null)))
     return;  // the object is a fake-null object --> early exit
 // now savely use "obj"


See this blog post for more details

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
avatar image elenzil · Apr 09, 2016 at 03:11 PM 0
Share

this is extremely helpful, thank you.

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

41 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

Related Questions

(Ads) initializationListener is null, you will not receive any callbacks 1 Answer

Navmesh event on navigation end 0 Answers

Login form: Do I have to set custom delegates to null in OnDestroy? 0 Answers

How can callback from shared object 0 Answers

How to make a callback function 3 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