Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!