I came across this line of code while doing Unity’s Multiplayer Networking tutorial:
var enemy = (GameObject)Instantiate(enemyPrefab, spawnPosition, spawnRotation);
What is the part “(GameObject)” called? Is there another way to write this same line of code?
Whenever you have a type name in parentheses like that, before a value, its called an Explicit Cast.
Casting an object is when you “convert it” - for lack of a better term - to a different type that it can be converted to.
You can cast ints to floats, you can cast all types to object, you can cas List to IList, etc:
int someInt = 10;
SomeClass someObject = new SomeClass("this is a parameter");
List<string> someListOfStrings = new List<string>();
float intAsFloat = (float)someInt;
object someClassAsObject = (object)someObject;
IList stringListAsIList = (IList)someListOfStrings;
intAsFloat == 10f : true
someClassAsObject == someObject : true
stringListAsIList == someListOfStrings : true