Be alert! A small trap of unityengine. Object in unity3d

Source: Internet
Author: User

Take a look at the following C # scriptCode:



Guess what the console came up?

In the bool Parameter Function, value info is: True

It must have been unexpected by many people, right?

There is no relation between the transform type and the bool type. How can we call testfunction (bool value? When I encountered this problem, the first reaction was that the compiler had a problem. Later, my colleague's machine had the same running result. So I continued to write the following code:


The running result is as expected. Void testfunction (system. object Value) is called ):

In the object Parameter Function, value info is: myclass

The problem still occurs on the unity3d class, that is, the transform. Then, let's look at its parent class. The top is the unityengine. object. After reading the metadata file of unityengine. object, I suddenly realized:


The object class of unity3d overload the implicit type conversion operator bool (other types can be reloaded, not just bool), so testfunction (Transform) actually calls this function, this overload function is used to determine whether the current object is not empty, which also conforms to the output information (that is, true ). Well, you accidentally step into this trap and the editor won't have any warning during the editing stage. What should I do if I want to call it normally? Use this method only:

Testfunction (transform as object );

Because system. object does not overload the type conversion operator bool, the output is as follows (I mounted this script to maincamera ):

In the object Parameter Function, value info is: main camera (unityengine. Transform)

Things have come to an end for the time being, but I personally feel like a trap. What do you think?


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.