I've ran into some unexpected behavior in c#. I'm basically trying to assign an action to a reference of another action, so that I can subscribe/unsubcrib methods to the referenced action at a later time. I don't want to have to know the class which implements the referenced action.
The problem is, the action that should be pointing to the action I want to listen to doesn't seem to actually point to it. I thought it would raise whenever the referenced action is raised but apparently that's not the case.
I probably have some misunderstanding of delegates. Could someone please tell me what I'm doing wrong? Is there a solution to what I am trying to achieve?
I appreciate any responses!
public class WaitForActionProcess : IProcess
{
public Action Finished { get; set; }
Action actionHandler;
public WaitForActionProcess(ref Action action)
{
actionHandler = action;
}
public void Play()
{
actionHandler += RaiseFinished;
}
public void RaiseFinished()
{
actionHandler -= RaiseFinished;
if(Finished != null)
{
Finished();
}
}
}
Example of use:
public class ReturnToMainMenuFrame : TutorialEventFrame
{
[SerializeField]
TutorialDialogueData dialogueData;
[SerializeField]
PointingArrowData arrowData;
[SerializeField]
TutorialDialogue tutorialDialogue;
[SerializeField]
PointingArrow arrow;
[SerializeField]
MainView mainView;
public override void StartFrame()
{
frameProcesses.Add(new ShowPointToUIProcess(arrow, arrowData));
frameProcesses.Add(new ShowDialogueProcess(tutorialDialogue, dialogueData));
frameProcesses.Add(new WaitForActionProcess(ref mainView.OnViewShown));
frameProcesses.Add(new HideDialogueProcess(tutorialDialogue, this));
frameProcesses.Add(new HidePointToUIProcess(arrow,this));
base.StartFrame();
}
}
Frame Base implementation:
public class TutorialEventFrame : MonoBehaviour {
public delegate void OnFrameEnded();
public event OnFrameEnded FrameEnded;
public List<IProcess> frameProcesses = new List<IProcess>();
public bool debugMode = false;
public virtual void StartFrame()
{
StartProcess(0);
}
void StartProcess(int processIndex)
{
if (processIndex < frameProcesses.Count)
{
int nextProcessIndex = processIndex + 1;
frameProcesses[processIndex].Finished += () => StartProcess(nextProcessIndex);
}
else
{
EndFrame();
return;
}
if (debugMode)
{
Debug.Log("Starting process: " + frameProcesses[processIndex] + " of processes: " + (processIndex + 1) + "/" + (frameProcesses.Count - 1) + " on frame: " + name);
}
frameProcesses[processIndex].Play();
}
public virtual void EndFrame() {
foreach (var process in frameProcesses)
{
process.Finished = null;
}
if (debugMode)
{
Debug.Log("frame: " + name + " finished");
}
frameProcesses.Clear();
if (FrameEnded != null) {
FrameEnded();
}
}
}