WDUK
WDUK

Reputation: 1524

How to add to a chain of methods by checking if statements

I don't know the right terminology for this but i have a simple C# code snippet which tweens some objects like this:

camera.gameObject.transform.DOMove(target,3.0f)
.SetEase(Ease.InOutQuad)
.OnComplete(animation.FadeIn);

But what i need to do is add another method to this chain based on a certain condition like this:

camera.gameObject.transform.DOMove(target,3.0f)                       
.SetEase(Ease.InOutQuad)            

  //the general idea
  if(visible == true){
  .OnStart(animation.FadeOut);
  }         

.OnComplete(animation.FadeIn);

Obviously this is a syntax error, but i do not know the correct way to handle something like this for the syntax.

How should i approach it?

Upvotes: 1

Views: 53

Answers (2)

Dovydas Šopa
Dovydas Šopa

Reputation: 2300

If you want to keep everything in one chain you can try using If extension:

internal static T If<T> (this T source, bool isTrue, Action<T> thenAction) {
    if (isTrue) {
        thenAction(source);
    }
    return source;
}

This extension will work if OnStart returns same camera object. Otherwise, If extension should be changed.

Then your code would look like this:

camera.gameObject.transform.DOMove(target,3.0f).
    SetEase(Ease.InOutQuad)
    If(visible == true, value => value.OnStart(animation.FadeOut)).
    OnComplete(animation.FadeIn)

If OnStart actually returns different object:

internal static T If<T> (this T source, bool isTrue, Func<T, T> thenFunction) =>
    isTrue ? thenFunction(source) : source;

Upvotes: 1

npinti
npinti

Reputation: 52185

You would need to place the entire chunk in your if-else statement, you cannot break it down:

if(visible == true){
  camera.gameObject.transform.DOMove(target,3.0f)                   
.SetEase(Ease.InOutQuad) .OnStart(animation.FadeOut).OnComplete(animation.FadeIn);
  }      
else {
  camera.gameObject.transform.DOMove(target,3.0f)                   
.SetEase(Ease.InOutQuad).OnComplete(animation.FadeIn);      
}   

Alertnatively:

var intermediateObject = camera.gameObject.transform.DOMove(target,3.0f)                   
    .SetEase(Ease.InOutQuad);

if (visible) {
    intermediateObject.OnStart(animation.FadeOut).OnComplete(animation.FadeIn);;
}
else {
    intermediateObject.OnComplete(animation.FadeIn);;
}

The var keyword means that you do not need to worry about the type of the object yourself, but then again, its usage does hinder readability (in my opinion).

Upvotes: 1

Related Questions