Search Unity

Repeatedly call a method based on a animation curve

Discussion in 'Scripting' started by wxxhrt, Jul 24, 2019.

  1. wxxhrt

    wxxhrt

    Joined:
    Mar 18, 2014
    Posts:
    163
    I am trying to figure out how repeatedly call a method based on the value of an animation curve (slowly decreasing in repetitions), to give the impression of for instance a fruit machine ticking over until it comes to a stop.

    Any help would be greatly appreciated!


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using DG.Tweening;
    5.  
    6.  
    7. public class RollRandomiser : MonoBehaviour
    8. {
    9.     public InstantiateRandomise ir;
    10.     public AnimationCurve animCurve;
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.        
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         if (Input.GetKeyDown("space"))
    22.         {
    23.             TriggerRoll();
    24.         }
    25.     }
    26.     void TriggerRoll()
    27.     {
    28.         if (DOTween.IsTweening("roller"))
    29.         {
    30.             DOTween.Kill("roller", false);
    31.         }
    32.         DOVirtual.Float(0, animCurve.length, animCurve.length, Roll).SetId("roller");
    33.     }
    34.  
    35.     void Roll(float f)
    36.     {
    37.         float value = animCurve.Evaluate(f);
    38.         StartCoroutine(InvokeMethod(Time.deltaTime, (int)value));
    39.     }
    40.  
    41.     void CallRandomise()
    42.     {
    43.         ir.Randomise();
    44.     }
    45.  
    46.  
    47.     public IEnumerator InvokeMethod(float interval, int invokeCount)
    48.     {
    49.         for (int i = 0; i < invokeCount; i++)
    50.         {
    51.             CallRandomise();
    52.  
    53.             yield return new WaitForSeconds(interval);
    54.         }
    55.     }
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    Instead of describing how you think you can accomplish your goal...

    How about describing what your goal is, and the proposed inputs you want to reach that goal (AnimationCurve in this case).

    Maybe we can help direct you in the right direction then... otherwise, looking at your code and calling 'StartCoroutine' every tick of the DOTween... well, that's going to result in overlapping coroutines.