Generics in Unity C#

I am having a lot of trouble with the syntax and the rules for using Generics. I am trying to make a structure, where different classes, can use the WaitAction class to disable input while a couroutine is running, an re-enable it once the coroutine is finished.

This example is a simplified version, and in reality I will not be using a count float to define the length of the coroutine, but the length will based on animations and translation.

Is what I am trying to do at all possible?

"Somehow use "T _ready" to change the "bool ready" in "Main Class" back to "true""

public class Main : Monobehaviour {

  WaitAction _waitAction = new WaitAction();

  public bool ready;
  float delay = 5f;

  void Update()
  {
    if(Input.GetMouseButton(0) && ready)
      {
          ready = false;
          StartCoroutine(_waitAction.SomeCoroutine((delay, this));
      }
  }


public class WaitAction {

    public IEnumerator SomeCoroutine<T>(float count, T _ready)
    {
        float time = Time.time;

        while(Time.time < time + count)
        {
            yield return null;
        }
        // Somehow use "T _ready" to change the "bool ready" in "Main Class" back to "true"
    }
}

Upvotes: 1

Views: 159

Answers (1)

David Arno
David Arno

Reputation: 43254

The solution is to constrain the generic type, such that the generic method knows how to set the ready flag. This is easily done using an interface:

public interface IReady
{
    bool ready { get; set; }
}

public class Main : Monobehaviour, IReady {

    ...
    public bool bool ready { get; set; }
    ...
}


public class WaitAction {

    public IEnumerator SomeCoroutine<T>(float count, T _ready) where T : IReady
    {
        ...
        _ready.Ready = true;
    }
}

Upvotes: 3

Related Questions