Hi, doc said that addcomponent is obsolet.
- I want to add colider to my prefab to detec colision, in js.
Thanks
Hi, doc said that addcomponent is obsolet.
Thanks
Adding a component by name is obsolete. It’s “bad” because it isn’t type safe - it can’t be validated at compile time.
As others have said, you can pass in the type. However the other answers are showing you incorrect syntax for doing so. The documentation you referenced shows the proper syntax:
void Start()
{
SphereCollider sc = gameObject.AddComponent(typeof(SphereCollider)) as SphereCollider;
}
In other words, since you’re passing in a type you must use the typeof
function to get the type.
The other way to do this is with generics
, and this also has an example in the documentation. This is arguably the “best” way.
void Start()
{
SphereCollider sc = gameObject.AddComponent<SphereCollider>() as SphereCollider;
}
If you were to do gameObject.AddComponent("Rigidbody")
, that would be obsolete and not recommended. However, if you were to do gameObject.AddComponent(Rigidbody)
that would not be. The first AddComponent function takes a string as its argument, which is the name of the class that will be added, in this case “Rigidbody”. The second takes a type as its argument, which is the actual type reference to the class that will be added. The second method is much more robust and less prone to failure. You can still use AddComponent, but make sure you’re passing in the type instead of type name (SphereCollider vs “SphereCollider”).
In the docs says: AddComponent with string is obsolete, instead use AddComponent with a type.
Example:
//Good, not obsolete.
function Start() {
var sc: SphereCollider = gameObject.AddComponent(SphereCollider) as SphereCollider;
}
//Bad, obsolete.
function Start() {
var sc: SphereCollider = gameObject.AddComponent("SphereCollider");
}
SpereCollider is a type. you need put the type in the method paramenter, not the string.
In c# would be typeof(MyType);