GameObject.SetActive
Activates/Deactivates the GameObject, depending on the given true or false value.
A GameObject may be inactive because a parent is not active. In that case, calling SetActive will not activate it, but only set the local state of the GameObject, which you can check using GameObject.activeSelf. Unity can then use this state when all parents become active.
Deactivating a GameObject disables each component, including attached renderers, colliders, rigidbodies, and scripts. For example, Unity will no longer call the Update() method of a script attached to a deactivated GameObject. OnEnable or OnDisable are called as the GameObject received SetActive(true) or SetActive(false) .
Деактивация Игровых Объектов
Чтобы временно удалить GameObject основной объект в сценах Unity, который может представлять персонажей, реквизит, декорации, камеры, путевые точки , и больше. Функциональность GameObject определяется прикрепленными к нему компонентами. Подробнее
См. в Словарь из вашего scene Сцена содержит окружение и меню вашей игры. Думайте о каждом уникальном файле сцены как об уникальном уровне. В каждой сцене вы размещаете свое окружение, препятствия и декорации, по сути проектируя и создавая свою игру по частям. Подробнее
См. в Словарь , вы можете пометить GameObject как неактивный.
Для этого перейдите в Инспектор окно Unity, в котором отображается информация о текущем выбранном игровом объекте, активе или настройках проекта. , что позволяет просматривать и редактировать значения. Дополнительная информация
Просмотрите в окне Словарь и снимите флажок слева от названия игрового объекта. Имена деактивированных игровых объектов отображаются в окне иерархии блеклыми.
Чтобы деактивировать GameObject с помощью скрипта, используйте метод SetActive. Чтобы узнать, является ли объект активным или неактивным, проверьте свойство activeSelf.
Деактивировать родительский игровой объект
Если вы деактивируете родительский игровой объект, вы также деактивируете все его дочерние игровые объекты, поскольку деактивация переопределяет параметр activeSelf для всех дочерних игровых объектов. Дочерние игровые объекты возвращаются в исходное состояние при повторной активации родителя.
Чтобы узнать, активен ли дочерний игровой объект в вашей сцене, используйте свойство activeInHierarchy.
Примечание. Свойство activeSelf не всегда верно, если вы проверяете дочерний объект GameObject, потому что, даже если он установлен как активный, вы могли установить один из его родительские игровые объекты в неактивные.
Выбранный игровой объект (куб) становится активным, но остается неактивным до тех пор, пока вы не сделаете его родительский игровой объект активным.
Включение и отключение объекта в коде С# Unity3d
![]()
Вы можете создать GameObject , в который будете добавлять звёзды как child, ну и хранить для удобства в List<ActiveStar> , скажем StarHolder :
![]()
Вообще, если я правильно помню, то необходимо обращаться к полю gameObject объекта. И тогда получится, что надо писать так:
Также у объекта есть поле activeInHierarchy, которая позволяет вам узнать активен ли данный gameObject в игре. На её основе можно написать следующее:
или activeSelf — выдает состояние активности данного GameObject’а.
то есть можно написать метод, который включает/выключает объект
и в любой момент, когда вам понадобится — им воспользоваться, например:
Ну еще можно (и полезно когда много объектов) заносить объект в список/массив, как пишет в соседнем ответе @Suvitruf и уже манипулировать им через него.
По коду в обновлении:
Нужно как раз вот это: «все выключены и надо чтоб одной по одной появились все»
При старте гасите все звезды (если они были включены) через цикл. А прям в самой корутине делаете следующее: в начале из ListStars отбираете те, которые еще не включены
4 ways to hide/show Canvas elements in Unity
When working with the Unity canvas, there are times when you’ll need to change the visibility of a UI element. For example, you might need make a dialog visible to the user and then hide the dialog when the user has interacted with it. Unity allows us to do this in different ways and they each have situations when they come in handy. Here are some of them:
1. Using GameObject.SetActive()
The SetActive method activates/deactivates a game object in the scene, depending on the Boolean value you pass to it as an argument.
One thing to note about this approach is that since the game object is deactivated, none of the components attached to it are enabled. So this method is not suitable when we have some code that we need to run whether the UI element is visible or not.
For example, we might be attempting to achieve data and view separation in our code by using a programming library like UniRx. We might have a Boolean reactive property like DialogOpen . We want a certain dialog in the scene to toggle its visibility based on the value of DialogOpen , so we subscribe to changes to DialogOpen from a Dialog script attached to the dialog. What if we try to implement it like this?
Unfortunately this code will not work as expected if the game object is set to be inactive in the scene by default. Because the object is deactivated, the Dialog component will not be enabled and so our Start() method never gets called.
We could fix this by enabling the dialog by default from the scene and then calling SetActive() to initially deactivate it from Start() . Since Start() is called before the first frame update the user doesn’t get to see the dialog just before we hide it.
2. Using Image.enabled
Another way to show/hide a UI element in the canvas is by setting the enabled property of its Image component. Of course this only works if the game object actually has an Image component attached to it, so it won’t work for things like text.
Using this method for our dialog now:
It’s also worth noting that this doesn’t affect the visibility of children of the game object, so this method isn’t helpful when you need to hide the object along with all its children.
3. Using CanvasGroup
The third way we’ll talk about is to the attach a CanvasGroup component to the UI element. CanvasGroup has some properties that you can set from the editor or from code.
The Alpha property controls the transparency of the UI element. The Interactable property, as the name implies, determines whether or not the element should accept our input when it detects it. Block Raycasts basically determines whether the element should detect any input at all.
Now let’s try this on our dialog. When the value of DialogOpen changes to false , we want the dialog to become invisible and allow us to interact with elements rendered behind it in the canvas.
4. Using CanvasElementVisibility
You can also use CanvasElementVisibility, a small Unity package with a script I wrote so you can avoid repeating yourself if you choose to use the method above.
Now we can shorten the previous code:
So these are 4 useful ways to hide or show a UI element in the Unity canvas.
Do you have any insights on even more approaches to doing this? Kindly leave a reply for me if so.