Если я отключу скрипт раньше, можно ли вызвать методы этого объекта, подписанного на событие другого класса, если я вызову событие позже? - PullRequest
0 голосов
/ 27 мая 2020

Я написал класс, который отвечает за создание интерактивного учебного пособия, у меня есть текстовая переменная, которая представляет собой текст, который показывает шаги учебного пособия, но когда игрок проигрывает и не завершил обучение, я хочу, чтобы gameobjet текста, который нужно деактивировать. ()

 using UnityEngine;
 using UnityEngine.UI;
 using System.Collections;

 public class TutorialHandler : MonoSingleton<TutorialHandler> , IObserver {

    public Toggle toggleTutorial;
    public Text tutorialText;
    public bool isInitialized;
    public float waitTime;
    private Combo combo;

   //delegate to wait for conditions to continue with the tutorial
    private System.Func<bool> onDeterminacion;

    //variable of the ui class that is responsible for determining whether or not to show the 
    //tutorial
    private UiHandler uiHandler;

    protected override void Awake()
    {
        base.Awake();

    }
    private void Start() {

        uiHandler = UiHandler.current;

        // toggleTutorial.isOn = uiHandler.showTutorial;
         toggleTutorial.onValueChanged.AddListener((value) => 
        {
            print(value);
            uiHandler.showTutorial = value;

        }
        );
        GameSceneController.current.observers.Add(this);
        GameSceneController.current.otherObservers.Add(this);

        // enabled = false;
        EventBroker.onHitPlayer = DieText;

    }
    private void OnEnable()
    {

    }
    public IEnumerator TutorialManager()
    {
        tutorialText.gameObject.SetActive(true);
        if (isInitialized)
        {
            tutorialText.gameObject.SetActive(false);
            yield break;
        }
        isInitialized = true;

        //Lineas 
        tutorialText.text = "Dibuja Lineas para jugar!";
        yield return new WaitForSeconds(2);

        tutorialText.text = "Solo puedes tener 2 lineas disponibles";
        yield return new WaitForSeconds(2);
        onDeterminacion += Obstacles;

        while (uiHandler.showTutorial)
        {
            if(tutorialText != null)
            tutorialText.gameObject.SetActive(true);

            yield return new WaitUntil(onDeterminacion);

            if (tutorialText != null)
            tutorialText.gameObject.SetActive(false);
        }
        enabled = false;
        isInitialized = false;
        onDeterminacion = null;
    }

     //method subscribed to onHitPlayer
     void DieText()
     {
       tutorialText.gameObject.SetActive(false); 

      }
     //much code here 
   ....
    //methods of iObserver interface
    public void Notify()
    {
        tutorialText.gameObject.SetActive(false);
        enabled = false;
    }

    public void Restart()
    {
        tutorialText.gameObject.SetActive(true);
        enabled  = true;
    }
}

Я использовал logi c подписки метода DieText () на событие, которое вызывается, когда игрок проигрывает, и этот же класс реализует интерфейс под названием «IObserver» с двумя методы Notify () и Restart (). в другом классе я сохраняю "tutorialHandler" в списке, чтобы я мог вызывать методы интерфейса в классе l oop.

public List<IObserver> observers = new List<IObserver>();
public void NotifyObservers()
    {

        for (int i = 0; i < observers.Count; i++)
        {
            observers[i].Notify();
        }

    }

это EventBrokerClass.

using System;
using System.Collections.Generic;

public static class EventBroker
{
    public static event Action onHitPlayer; //event called when the player loses

    public static void ExecuteoOnHitPlayerEvent(Player p)
    {
        if (onHitPlayer != null && !Player.isDoublePlayer)
        {
            PersistentData.Guardar(UiHandler.current);
            GameSceneController.current.NotifyObservers(); //I notified the objects IObserver
            onHitPlayer(); //call the event
        }
        else
        {
            p.Die();
        }
    }
}

Сначала я вызываю for l oop из списка Iobserver, а затем вызываю событие onHitPlayer.

, но кажется, что когда я ранее деактивировал скрипт, методы, на которые я подписался, не называется. (извините, здесь нет носителя языка :))

...