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
1
Question by YoungDeveloper · Jun 22, 2016 at 09:41 AM · c#optimizationgetcomponentcast

Upcast vs GetComponent

Has anyone any idea of what might be more optimized. Consider this example.

 public abstract class BaseMono: MonoBehaviour {
 
 }

And classes which inherit from this base class.

 public class A: BaseMono{
 
 }
 
 public class B: BaseMono{
 
 }

Inside BaseMono i have a method which finds type inheriting this. Which of these methods would execute this resolve faster.

  • TellMe1() Uses getcomponent

  • TellMe2() Uses upcast

  • TellMe3() Uses is keyword, but returns only logical yes or not, instead of possible valid instance.

Upcast and is are quite instant, but i am not sure how heavy is getcomponent behind the scenes. Unity development enviroment kinda suggest me to use getcomponent, because of mono being the root of this chain, but it feels like it isnt the fastest. is keyword sure is the most readable though.

 public abstract class BaseMobo: MonoBehaviour {
 
 public void TellMe1(){
     if(gameObject.GetComponent<A>() != null) {print("A is parent"); return;}
     if(gameObject.GetComponent<B>() != null) {print("B is parent"); return;}
 }
 
 public void TellMe2(){
     if( ((A)this) != null) {print("A is parent"); return;}
     if( ((B)this) != null) {print("B is parent"); return;}
 }

 //Is not the same, but useful
 public void TellMe3(){
     if( this is A) {print("A is parent"); return;}
     if( this is B) {print("B is parent"); return;}
 }
 
 }















Comment
Add comment · Show 2
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 Bunny83 · Jun 22, 2016 at 09:59 AM 1
Share

$$anonymous$$eep in $$anonymous$$d upcasting goes up the inheritance chain. At the top of the chain is the type "object" at the bottom is your concrete type. Upcasting is always safe (treating a concrete class as a base class). Downcasting on the other hand can fail (casting a base class reference to a more concrete class)

The normal cast will throw an invalid casting exception if the type can't be casted into the specifid type.

The as-cast will return null is the cast is not possible.

So only use a "normal" case when you are sure that the cast is possible. It's common to pair the "is" operator with a normal downcast or to use an as downcast with a null check.

ps: all your examples are lacking curly brackets for your if statements. Without brackets an if only affects the next statement that directly follows the if. So your "return" statements are outside the if and will execute unconditionally.

You should avoid placing the statement in the same line as the if. In some cases it makes sense but usually it's better to place it in the next line, indented.

So your if in line 15 would look like this:

 if( this is A)
     print("A is parent");
 return;

while you want

 if( this is A) {
     print("A is parent");
     return;
 }
avatar image YoungDeveloper Bunny83 · Jun 22, 2016 at 10:04 AM 1
Share

Yeah, downcasts should be treated more carefully. You are flooding this with answers, im blushing. Thank you for your time bunny, have a good day. Upvoted everything i can ;)

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Bunny83 · Jun 22, 2016 at 09:53 AM

The best and safest way is using either an "is" check in combination with a down cast or an "as" cast. GetComponent makes no sense as you get in trouble if there are multiple instances of a component on the same gameobject.

So either use:

 if (this is A)
 {
     A a = (A)this; // here the down cast is safe since we know it's an "A"
     // A specific stuff
 }
 else if (this is B)
 {
     B b = (B)this; // here the down cast is safe since we know it's an "A"
     // B specific stuff
 }

Or use

 A a = this as A;
 if (a != null)
 {
     // A specific stuff
 }
 
 B b = this as B;
 if (b != null)
 {
     // B specific stuff
 }

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 YoungDeveloper · Jun 22, 2016 at 10:00 AM 0
Share

I have single instance per gameobject root, which is validated in Reset(). But it still logially makes sense to not use getcomponent, which am happy about. $$anonymous$$y thoughts exactly, thanks!

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

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

Difference between GetComponent 2 Answers

Forcibly halt movement of slow rigidbodies, but not falling ones. (2D) 1 Answer

[Solved] How to find a variable using the value of another variable? 1 Answer

How can I access variables from other scripts? c# 2 Answers

Can this script be better optimized? 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