Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Evento para detectar ActiveSelf

¿Hay un evento de escucha para detectar si un objeto se configura como inactivo desde el estado activo o como activo desde el estado inactivo? No quiero agregarlo en la actualización ya que habrá varias llamadas y afectaría el rendimiento de mi juego. Entonces, ¿hay alguna alternativa para esto?

 public GameObject Go_1; public GameObject Go_2; void Update () { if (Go_1.activeSelf) { } else if (Go_2.activeSelf) { } }
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Sí, prueba con OnEnable y OnDisable .

 // Implement OnDisable and OnEnable script functions. // These functions will be called when the attached GameObject // is toggled. // This example also supports the Editor. The Update function // will be called, for example, when the position of the // GameObject is changed. using UnityEngine; [ExecuteInEditMode] public class PrintOnOff : MonoBehaviour { void OnDisable() { Debug.Log("PrintOnDisable: script was disabled"); } void OnEnable() { Debug.Log("PrintOnEnable: script was enabled"); } void Update() { #if UNITY_EDITOR Debug.Log("Editor causes this Update"); #endif } }
over 4 years ago · Santiago Trujillo Relatório

0

Podría implementar algo usando el método de Update como, por ejemplo

 public class ActiveSelfWatcher : MonoBehaviour { private Dictionary<ActiveSelfProvider, bool> _lastActiveSelfState = new Dictionary<ActiveSelfProvider, bool>(); private void OnObjectBecameActive(GameObject obj) { Debug.Log($"{obj.name} became active!", this); } private void OnObjectBecameInactive(GameObject obj) { Debug.Log($"{obj.name} became inactive!", this); } private void Update() { // Iterate through all registered instances of ActiveSelfProvider foreach(var provider in ActiveSelfProvider.Instances) { // pre-cache the GameObject reference var obj = provider.gameObject; // pre-cache the current activeSelf state var currentActive = obj.activeSelf; if(!_lastActiveSelfState.TryGetValue(provider)) { // we don't know this provider until now // TODO here you have to decide whether you want to call the events now once for this provider or not // TODO otherwise it is only called for providers you already know and changed their state } if(currentActive != _lastActiveSelfState[provider]) { // the state is not the one we stored for this instance // => it changed its states since the last frame // Call the according "event" if(currentActive) { OnObjectBecameActive(obj); } else { OnObjectBecameInactive(obj); } } // store the current value _lastActiveSelfState[provider] = currentActive; } } }

Esta es su clase de observador que actualmente ya tiene de todos modos.

Luego, en todos los objetos que desea poder ver, usa

 public class ActiveSelfProvider : MonoBehaviour { private static readonly HashSet<ActiveSelfProvider> instances = new HashSet<ActiveSelfProvider>(); public static HashSet<ActiveSelfProvider> Instances => new HashSet<ActiveSelfProvider>(instances); private void Awake() { // register your self to the existing instances instances.Add(this); } private void OnDestroy() { // remove yourself from the existing instances instances.Remove(this); } }

Si esto es "lo suficientemente eficiente" para su caso de uso, tendría que probar;)


Si quieres ir súper elegante, alguien una vez hizo un Transform Interceptor ... un truco bastante desagradable que en el tiempo de compilación anula partes de los configuradores de propiedades Transform incorporados de Unity para enganchar las devoluciones de llamada.

Probablemente se podría crear algo como esto también para SetActive ;)


Nota: escrito en el teléfono inteligente, pero espero que la idea se aclare

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda