Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda