Lerp in a function not update need help please

i need to run the lerp in a function and NOT in update, i have included 2 scripts one that runs in update to show what i need to replicate in a non update function, the other script shows the problem when lerp is run in a function, just create 2 cubes and put one script on each, run and press the space bar to see the problem, i have tried to use a co-routine ienumerator but still cannot get it to run like it does in the update script, i have been tearing my heair out trying to sort this but it just wont work for me.

as you will see i need to rotate the cube by 90 degrees on a random axis, but for my game i need it to run in a function and not in update

any help greatly thanked

csharp:


using UnityEngine;

public class ROTATE9 : MonoBehaviour
{
public float smooth = 1f;

private Vector3 turn;

private Quaternion targetRotation;
void Start(){
targetRotation = transform.rotation;
}

void Update () {

if(Random.value<0.5f)
turn=Vector3.up;
else
turn=Vector3.left;

if (Input.GetKeyDown (KeyCode.Space)) {
targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP / FORWARD / OR LEFT
}
transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
print(transform.localEulerAngles.y);
}

}


using UnityEngine;

public class ROTATE11 : MonoBehaviour
{
public float smooth = 1f;

private Vector3 turn;

private Quaternion targetRotation;
void Start(){
targetRotation = transform.rotation;
}

void Update(){

if (Input.GetKeyDown (KeyCode.Space)) {
Rotate ();
}
}

void Rotate () {

if(Random.value<0.5f)
turn=Vector3.up;
else
turn=Vector3.left;

targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP / FORWARD / OR LEFT

transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
print(transform.localEulerAngles.y);
}

}


sorry for posting the scripts as text as i could not work out how to post the scripts properly

thank you

There is a pinned thread in the forums that explains how to add code in the forums properly :slight_smile:

thank you, i have done it before but for some reason it would not post the thread, thats why i did put the apology

Here it is reformatted so we can read it:

using UnityEngine;

public class ROTATE9 : MonoBehaviour
{
    public float smooth = 1f;

    private Vector3 turn;

    private Quaternion targetRotation;
    void Start(){
        targetRotation = transform.rotation;
    }

    void Update () {

        if(Random.value<0.5f)
            turn=Vector3.up;
        else
            turn=Vector3.left;

        if (Input.GetKeyDown (KeyCode.Space)) {
            targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP / FORWARD / OR LEFT
        }
        transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
        print(transform.localEulerAngles.y);
    }


}
using UnityEngine;

public class ROTATE11 : MonoBehaviour
{
    public float smooth = 1f;

    private Vector3 turn;

    private Quaternion targetRotation;
    void Start(){
        targetRotation = transform.rotation;
    }

    void Update(){

        if (Input.GetKeyDown (KeyCode.Space)) {
            Rotate ();
        }
    }



    void Rotate () {

        if(Random.value<0.5f)
            turn=Vector3.up;
        else
            turn=Vector3.left;

        targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP / FORWARD / OR LEFT

        transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
        print(transform.localEulerAngles.y);
    }

}

You will notice that your code is very different between the 2.

In the first, you are always updating the rotation, no matter what. Allowing the lerp to occur over time.

In the next one, you only call Rotate, if and only if, the Space bar ‘Down’ state is true. Which is just a single time for every press of the space bar.

Very different functionality.

What is it you expect to occur? Do you want it to act like the prior? Why is it that it can’t be in the Update function? Why is it you can’t just copy the same code into the Rotate function and just call it from Update?

yes i need the lerp in the function to act like it does in the update, but i cant get it to stay running until the lerp is complete, i have tried to do it in a co-routine but still cannot get the lerp to complete, i tried a while loop but just cant get it to act like it does in the update, i cant use it in game in update it has to be in a function.

i tried to call the function from the update but it still wont complete the lerp until it rotates completely, i cant use it in the update as the script needs to be on 100 prefabs and constantly runs and slows the game to a crawl, so i need to call it only when needed which i cant do in the update, so it has to be in a function or a co-routine ienumerator, if anyone can get the co-routine working that would be fantastic as it just wont work for me i just cant understand why i cant get the lerp to continue until finished.

i only used the spacebar to start it off, the function will eventually be called by another script from a collision to start the rotation on the other object.

@lordofduct you say “Why is it you can’t just copy the same code into the Rotate function and just call it from Update?”

this wont work as when the function is called from update it still does not run the function long enough for the lerp to finish, so how can lerp be used in a function outside of update, i have tried using t time.deltatime to keep a loop going but it still wont work, i have tried using a co-routine and the lerp still does not complete, i just need a bit of help showing me how this can work as i am totally stuck

thank you

You have different code in your Rotate function then you do in the Update function in the prior.

Do you not see that the code is distinctly different?

the only difference is the press spacebar code, which is there to call the function once from update, if you remove that and just let update constantly call the rotate function it still does not behave the same as when it is just in update, cant you see that by trying the code, put 2 seperate boxes in the scene side by side, one code on each and press the spacebar, see the difference?

when the lerp is called in update it runs to the end once, when update calls it in a seperate function it goes mental and does not do a complete run once to the end of the lerp…

And that’s a big difference!

This would be an exact copy:

using UnityEngine;

public class ROTATE11 : MonoBehaviour
{
    public float smooth = 1f;

    private Vector3 turn;

    private Quaternion targetRotation;
    void Start(){
        targetRotation = transform.rotation;
    }

    void Update(){
        Rotate();
    }



    void Rotate () {

        if(Random.value<0.5f)
            turn=Vector3.up;
        else
            turn=Vector3.left;

        if (Input.GetKeyDown (KeyCode.Space)) {
            targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP / FORWARD / OR LEFT
        }
        transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
        print(transform.localEulerAngles.y);
    }

}

It would act the same way.

But by wrapping the ‘GetKey’ condition around which Roate gets called is significantly different code.

This code may look different, but is actually more similar than your existing code, and work just as fine, if not better (since we aren’t constantly calculating ‘turn’):

using UnityEngine;

public class ROTATE11 : MonoBehaviour
{
    public float smooth = 1f;

    private Quaternion targetRotation;
 
    void Start(){
        targetRotation = transform.rotation;
    }

    void Update(){
        Rotate();
    }
 
    void Rotate () {
        if (Input.GetKeyDown (KeyCode.Space))
        {
            Vector3 turn;
            if(Random.value<0.5f)
                turn=Vector3.up;
            else
                turn=Vector3.left;
            targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP /
        }
        transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
        print(transform.localEulerAngles.y);
    }

}

Though I don’t understand why you need it outside the ‘update’ function, it’s not getting you any benefits. If it’s because you want to separate the rotation logic from the input logic… then do this:

using UnityEngine;

public class ROTATE11 : MonoBehaviour
{
    public float smooth = 1f;

    private Quaternion targetRotation;
   
    void Start(){
        targetRotation = transform.rotation;
    }

    void Update(){
        if (Input.GetKeyDown (KeyCode.Space))
            InputLogic();
        Rotate();
    }
   
    void InputLogic()
    {
        Vector3 turn;
        if(Random.value<0.5f)
            turn=Vector3.up;
        else
            turn=Vector3.left;
        targetRotation *= Quaternion.AngleAxis(90, turn); // USE 90 or -90 AND UP /
    }
   
    void Rotate () {
        transform.rotation= Quaternion.Lerp (transform.rotation, targetRotation , 10 * smooth * Time.deltaTime);
        print(transform.localEulerAngles.y);
    }

}

I’m pretty sure what OP meant by “outside of Update” is to rotate in a coroutine that will animate until it reaches its end. different from the original where its always rotating. here, he wants the rotation to wait for an input event before it can begin rotating.

    private Coroutine handle;
    public float duration = 0.5f;

    void Update()
    {
      
        if (Input.GetKeyDown (KeyCode.Space))
        {
            if(handle!= null) return;

            handle = StartCoroutine(Rotate());
        }
    }

    IEnumerator Rotate ()
    {
        Vector3 turn;
        if(Random.value<0.5f)
            turn=Vector3.up;
        else
            turn=Vector3.left;
 
        float lerp =0;
        var startRot = transform.localRotation;
        var targetRot = startRot * Quaternion.AngleAxis(90, turn);
        while( lerp < 1 && duration >0)
        {
            lerp = Mathf.MoveTowards(lerp, 1, Time.deltaTime / duration);
            transform.localRotation = Quaternion.Slerp(startRot,targetRot , lerp);
        }
        transform.localRotation = targetRot;
        handle = null;
    }

although like @lordofduct said, theres no reason why you can’t do this in Update, aside from preference.

1 Like

I wasn’t going to try to get into Coroutines if OP wasn’t able to see the difference between their 2 versions of code.

There was a fundamental flaw in the logic that I felt was more relevant.

@JoshuaMcKenzie , you have it right, i need it in a coroutine as in the original it constantly rotates, so you have understood exactly why i need to have it in a seperate function/coroutine. the reason is that the script/function will be called by a seperate object upon collision, so i did not need it to constantly run the code.

thanks

i will check the code later, just going out right now, but thanks for all the posters for your help

@JoshuaMcKenzie Your script brings an error in unity, it says “error cs0161 not all code paths return a value”

this is back at that fundamental flaw I was talking about…

You’re not reading your errors or paying attention to the code logic, and instead of attempting to resolve the issue… you’re just coming here and saying “it doesn’t work”.

Why doesn’t it work?

OK… what line of code does this say it happens? I’m willing to bet it’s the ‘Rotate’ method, since it’s the only method that has a return type.

Why? Well the Rotate path expects an IEnumerator to be returned.

And it doesn’t.

Usually in these cases you’re creating an iterator function… which means you ‘yield return’ something.

But where? Where does it logically fit? Well the yielding waits a frame (or longer if yielding an object like a WWW). So we’re yielding to tick frames forward… when would we most likely do that? In the code that updates the orientation, which is in the while loop.

So try sticking a yield return null in the while loop.

@[lordofduct thats not my script with the error, its joshuaMcKenzie, script, so how am i to know what the error is?](https://forum.unity3d.com/members/lordofduct.66428/)

read the error

sure, this is joshua’s code, but the prior code wasn’t

also, read my post, I answer your problem

Here is the full error: Assets/ROT.cs(21,14): error CS0161: `ROT.Rotate()': not all code paths return a value, i never usually use coroutines this is why i am a bit unsure of the way they work, so i thank you for your help

EDIT: fixed it thank you

Yes it is my code and I did forget something in it, but as soon as I read the error I knew exactly what I forgot. that is what @lordofduct is trying to get at. This is a relatively simple error to fix and it’s likely something that you will encounter across several times in the future.

we both understand the importance of you being able to figure out such a simple error and resolving it on your own, otherwise you’re not going to become a better programmer. which is why he didn’t simply just give you the answer, just hints.

thanks for both your help, now have it working using the ienumerator, your help was very much apreciated…

I have had similar issues. Lerp and myAngles don’t even highlight in VisualStudios, and yes I already manually messed around in editor to make sure its looking at Visual Studios. Its annoying this constantly happens.