If I add a Component to a GameObject using gameObject.addComponent();, and I want to remove that component from the MyComponent C# file, is there anyway I can do something like:
Destroy(this);
instead of:
Destroy(gameObject.GetComponent<MyComponent>();
I know the latter works, but it just bugs me that I have to specify the name of the component that I am in.
Hello, why I see "anonymous" in text? Is it bug in Unity forum?[204692-screenshot-2023-02-13-162230.png|204692] Thank you for supporting from Unity team.
Keep in mind that this will only destroy the component but keep the GameObject and all other components. The Destroy method works with all instance-references that are derived from UnityEngine.Object. This includes GameObjects, Components, Meshes, Materials, …
Unfortunately they removed the hierarchy view from the documentation. With it it was easy to see all classes derived from a certain base class like Object, Collider, Renderer, …
edit
Actually your first version is the more reliable one since if the GameObject holds multiple instances of the same component, only the first one is returned and that isn’t necessarily the instance invoking GetComponent.
@Evorlor: Uhm with "actual script" you mean the class itself? That's not possible since all classes are compiled into one (a few) DLL assembly files which can't be altered at runtime. Destroy(this) will remove the script instances that is invoking that line.
Hello, why I see "anonymous" in text? Is it bug in Unity forum?[204692-screenshot-2023-02-13-162230.png|204692] Thank you for supporting from Unity team.
– LuongCongDan