Как получить ссылку / добавить / отключить / удалить компонент из скрипта
Приветствую начинающих разработчиков Unity. В данной статье мы рассмотрим сразу четыре возможности, которые можно реализовать с компонентами объекта, через скрипт, а именно: получение ссылки на компонент, добавление компонента, отключение компонента и удаление компонента.
Давайте пройдёмся по порядку.
Получение ссылки на компонент
Предположим, у нас имеется переменная obj, которая хранит в себе ссылку на наш объект. И нам необходимо получить ссылку на компонент данного объекта, например, на компонент Rigidbody. Для этого воспользуемся методом GameObject.GetComponent.
Тепер в переменной _rb у нас имеется ссылка на компонент Rigidbody, объекта obj. Так же убедитесь в том, что компонент, на который вы хотите получить ссылку, добавлен к Вашему объекту, иначе данный код работать не будет.
Добавление компонента
Как и в предыдущем примере, предположим, у нас имеется переменная obj, которая хранит в себе ссылку на наш объект.
Там нам необходимо добавить компонент для нашего объекта. Для этого нам понадобится метод GameObject.AddComponent. Воспользуемся им, добавив компонент, например, Rigidbody:
Готово! К объекту obj мы добавили компонент Rigidbody, и в переменную _rb записали ссылку для её хранение. Но на самом деле хранить ссылку на добавленный компонент не обязательно, поэтому, Вы можете обойтись и без этого.
Отключение компонента
Отключение и включение компонента используется довольно часто, для временного отключения или включения его свойств.
Предположим, что у Вас имеется переменная _rb, которая хранит в себе ссылку на какой-либо компонент.
У любого компонента имеется свойство enabled, которое принимая значения true и false, включает и отключает компонент соответственно. Воспользуемся им:
Данный код отключит Ваш компонет. А чтобы его опять включить, поменяйте значение true на false.
Удаление компонента
Удаление компонента, пожалуй, самое простое из всех тем этой статьи. За удаление компонента отвечает метод Destroy.
Так же убедитесь, что в переменной _rb имеется ссылка на Ваш компонент, который Вы хотите удалить.
На этом всё, теперь Вы умеете работать с компонентами 🙂 Если остались вопросы, задавайте их в комментариях.
Enable/disable a GameObject component from a script [Unity3D]
I need to take the value of a boolean (put in a variable called «bouclier») set in one script to enable or disable a GameObject.
The variable is in game object Player (bottom right here):

And I need to enable of disable this game object («Bouclier01»):

To do this, I attached a script to game object «Bouclier01». Here it is:
I must be missing something, because this comes up with this error message:
Unity как отключить компонент через скрипт
I need to take the value of a boolean (put in a variable called «bouclier») set in one script to enable or disable a GameObject.
The variable is in game object Player (bottom right here):

And I need to enable of disable this game object («Bouclier01»):

To do this, I attached a script to game object «Bouclier01». Here it is:
I must be missing something, because this comes up with this error message:
ACTIVATE and DEACTIVATE GameObjects through CODE in Unity
Introduction – Why activate and deactivate GameObjects?
GameObjects are the objects that can be placed in a scene in Unity, the simplest gameobject has at least a Transform component assigned, that allows to know its position, rotation and scale. You can add components to these GameObjects and give them a more specific behavior. For example, a Camera in Unity is an empty GameObject to which we add the Camera component and the AudioListener component.
When a GameObject is active in the hierarchy and the game is running, Unity periodically updates each of its components and executes some other functions, all this automatically. If we deactivate the GameObject, this process will not take place and we will achieve the effect that the GameObject disappears from the scene.
Unity Remove Components Attached to GameObjects

Tips and Tricks: Remove Components Attached to GameObjects in Unity
Introduction
Using the power of components to drive game design is what makes developing with Unity so flexible and easy to use. Building around singular behaviors and reusing them across your game makes for better code that is easy to understand. There are tons of literature on how to add components at runtime to modify the behaviors of your GameObjects. What is a little harder to find is, how to remove behaviors. How does Unity remove components during runtime? What does it take and what is the best way to achieve deleting behaviors without sacrificing performance?
In this Tips and Tricks: Unity Remove Components we are going to show you how to properly remove, destroy, and disable components. As well as review the best practices for writing performant code that does what you expect.
Remove Component With the Destroy Method
The first way you can remove components is by destroying them. This will permanently remove the component and all associated settings from the GameObject.
The destroy method can be called directly on a component that has been retrieved with GetComponent. The example here uses the generic method. This uses the diamond notation to specify that the type we are looking for is ParticleSystem.
Destroy Component By Name
You can also use the component’s name to destroy it. This once again uses GetComponent to retrieve the component. While this method is a possibility, it is not type safe and can lead to some irregularities under certain circumstances.
However, it is useful in scenarios where you only have access to a list of types in string format. For example, if you had a game that randomly removed abilities from the player. You could store the component types in a string list and get the component name by random index. This situation would require the string method.
Destroy Component by Type in Unity
Next, Unity can remove components by specifying the type of the component. Typeof is a type safe way of getting a component. You can trust it will always return the component you specified.
Remove Component Stored in Variable
Additionally, destroy will work on components you have cached in variables. All you have to do is use the helper method GetType() to specify the component to remove.
Destroy Component Vs Disable Component
Now, you may find yourself in a situation where you need to remove a component from a GameObject but only temporarily. Adding a new component means you have to reconfigure any parameters that may have been set up originally. This is a lot of wasted work for destroying a component.
Disable components instead. When a component is disabled it stops functioning and retains all of its values when disabled. Also, the lifecycle method OnDisable will be called when the component is disabled meaning you can trigger other logic to happen as your behavior is removed. OnEnable will also be triggered if you decide to enable the component later. This will give the ability to update any connections or settings before the normal game logic is applied.
Furthermore, when you disable components instead of destroying them, you do not create overhead and garbage that will bog down your game. It is the same reason your game will perform better using object pooling over instantiating and destroying GameObjects over and over.
How to Disable Components
Unity does not provide a method for disabling and enabling components. Instead, they provide access to active status through the use of a property. Properties essentially act as both a getter and setter method. We can change the status like so.
We can easily set up a switch method to cycle back and forth between enabled and disabled by setting it to the opposite of itself. Neat.
Unity Remove Component Example
We have created a simple scene to demonstrate how these methods work. The scene has one GameObject with a sprite renderer and particle system attached. The input system has been configured to trigger each of the methods above.


Trigger the DisableComponentSwitch button and watch the SpriteRenderer turn off. Notice the component is still attached to our GameObject. Hit it again and the sprite will reappear.
Now, enter the input for one of the destroy methods. The particles disappear and the component is no longer attached.

And now you are ready to remove, destroy, and disable components in the games you create with Unity. Thank you for stopping by. Stick around and check out more of our tutorials or posts like our piece on Unity’s GetComponent method for Accessing, Storing, and Modifying Components. Also, leave a comment telling us what you liked or did not like about the tutorial. Was it easy to follow along? What do you want to learn next? As always, check out some of our published apps below.