Search Unity

Consistent results with mathf.Sin() on respawning gameobjects?

Discussion in 'Scripting' started by masky007, Apr 18, 2019.

  1. masky007

    masky007

    Joined:
    Mar 21, 2019
    Posts:
    2
    Hi,

    I am using Mathf.Sin() to move an enemy, the problem is that when i respawn with SetActive false/true ( i return the gameobject to its original position) the Mahf.sin() function at a given time has a different value (which is to be expected)- thus sometimes making the gameobject start moving downwards and sometimes upwards from it's starting position, depending the sine function return value at the given moment.

    So how can i make that when i activate my gameobject i get the Sin() function always return the same value?

    Thanks
     
  2. jschieck

    jschieck

    Joined:
    Nov 10, 2010
    Posts:
    429
    when you enable the object store the time

    Code (CSharp):
    1. float startTime;
    2.  
    3. private void OnEnable()
    4. {
    5.     startTIme = Time.time;
    6. }
    Then when calling Sin, use the current time minus startTime, then you'll get the same result when the objects are re-enabled.

    Code (CSharp):
    1. float offset = Mathf.Sin(Time.time - startTime);