The difference between two version of GetComponent

Hi,

when trying to replace the javascript from the book “Game Development with Unity” by C# script,

the generic version works well to get the component (the script), but the non-generic version doesn’t work. (get null)

So can anyone explain the difference between them?

The generic version is
Widget_Inventory widgetInventory = (Widget_Inventory)collider.GetComponent<Widget_Inventory>();

The non-generic version is
Widget_Inventory widgetInventory = (Widget_Inventory )collider.GetComponent(“Widget_Inventory”);

Widget_Inventory is a Widget_Inventory .cs script attached on Widget gameObject.

Please let me know if my question or data is unclear.

Thanks

if either returns null its because that component is not on the given collider.

Use the generic version when you can.

Only reason the string overload would return null and the other not would be if you made a spelling error on the string.

No it is not. That cast is useless. Instead, it is

Widget_Inventory widgetInventory = collider.GetComponent<Widget_Inventory>();

It cold be. But if you wanted to match what the generic version, which is what you used to have to do, you would use:

Widget_Inventory widgetInventory = collider.GetComponent(typeof(Widget_Inventory)) as Widget_Inventory;