- Home /
How should I use the Generic versions of GetComponent<T> and AddComponent<T>?
How should I use the Generic versions of GetComponent and AddComponent?
Are you asking about the generic versions of GetComponent and AddComponent? if so, edit your answer to include this, and you'll probably have the negative votes changed to positive (I hope!)
Answer by duck · Oct 13, 2010 at 08:56 AM
Fromt the <T>
mentioned in the title, I assume Showken is asking specifically about the Generic versions of the component commands, namely:
GetComponent<T>
AddComponent<T>
These are available in C# (and Unity's Javascript since Unity 3.0), and they are useful in C# because they avoid the need for the "typeof" keyword when specifying the type, and having to cast the result which is returned as an Object by the non-generic versions of these methods.
For example, without the Generic versions, these commands look like this written in C#:
Enemy enemy = (Enemy) GetComponent(typeof(Enemy));
bullet = (ProjectileScript) projectile.AddComponent(typeof(ProjectileScript));
Contrasted with the Generic versions, which look like this:
Enemy enemy = GetComponent<Enemy>();
bullet = projectile.AddComponent<ProjectileScript>();
Much nicer!
Generics actually do work in Javascript with Unity 3.0, but you must use a "." between the function/constructor name and the angle brackets, ie. "GetComponent. ()" The change is described in http://unity3d.com/support/documentation/$$anonymous$$anual/$$anonymous$$onoUpgradeDetails.html
Wow, nice! Hadn't read that yet. I'd better update my old wiki pages and blog posts on the subject!
I am sorry!there are some problem I don't understand!follow three codes: 1: Enemy enemy = (Enemy) GetComponent(typeof(Enemy)); 2: Enemy enemy = GetComponent(); 3: Enemy enemy=new Enemy();; what is the different?
Answer by SrBilyon · Oct 13, 2010 at 08:41 AM
Check here for how to use "Component" in scripting: http://unity3d.com/support/documentation/ScriptReference/Component.html
Answer by Ashkan_gc · Oct 13, 2010 at 08:45 AM
as i know there is not any usecase that you might want to use it. you can create script components or create components like (Rigidbody) and call AddComponent to add the created component to a gameObject but i can not understand why you should use Component alone.
Your answer
![](https://koobas.hobune.stream/wayback/20220613075501im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to GetComponent from Class that uses Generics 1 Answer
Type of a script 1 Answer
Reference Not Set toInstance of Object 1 Answer
Sprint Script 3 Answers