Unity converts data types with brackets and as

There is a difference between Unity using parenthesis (type) transformation and as type transformation.


Instantiate the prefab:

GameObject go = Instantiate(perfab) as GameObject; 

GameObject go = (GameObject)Instantiate(perfab); 


1. The object instantiated by Instantiate is of Object type. If no type conversion statement is added, an error may be reported, so (GameObject) needs to be forcibly converted to GameObject.

2. Use parentheses to convert, an exception will be thrown if it fails, applicable scope: reference type , value type

3. Use the as operator to convert. If it fails, it will only return a null value and no exception will be thrown. Scope of application: reference type    Not applicable: value type  . Using as can reduce the negative impact of conversion failure, such as: error reporting and crash.

Note: In some C# editors (such as: Rider), it will prompt that as GameObject is a redundant statement, depending on the specific situation.

Guess you like

Origin blog.csdn.net/lcjok9/article/details/128679806