Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Need help with a simple platform moving.

Discussion in 'Scripting' started by Skalldyrssuppe, Nov 21, 2017.

  1. Skalldyrssuppe

    Skalldyrssuppe

    Joined:
    Nov 14, 2017
    Posts:
    1
    its just supposed to move a gamobject upwards using the FlyttOpp() method and the flipp the bool oppover so the next time it will call the FlyttNedover() method. i sort of works but thereis two issues i need help with here(with probably the same fix)
    1. the speed is out of controll if i set fart to 15 or 0000.8 its still really fast
    2. the debug.log is fireing of like crazy telling me that the WaitforSeconds issent working properly even though it does wait 5 seconds befor moving back.

    please help me ye wise ones.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class flytt_ting : MonoBehaviour {
    public Transform ting;
    public float fart = 0.0008f;
    public int skritt = 10;
    private bool oppover = true;

    IEnumerator FlyttOpp()
    {
    yield return new WaitForSeconds(5f);
    int i = 0;
    Debug.Log("flytter opp");
    while (i<skritt)
    {
    ting.transform.Translate(0,fart*Time.deltaTime,0,Space.World);
    i++;
    }
    oppover = false;
    }
    IEnumerator FlyttNed()
    {
    yield return new WaitForSeconds(5f);
    int i = 0;
    Debug.Log("flytter ned");
    while (i < skritt)
    {
    ting.transform.Translate(0, -(fart * Time.deltaTime), 0, Space.World);
    i++;
    }
    oppover = true;
    }

    // Update is called once per frame
    void Update () {
    if (oppover)
    {
    StartCoroutine(FlyttOpp());

    }
    if (!oppover)
    {
    StartCoroutine(FlyttNed());
    }

    }
    }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Please look at this page for a moment and see how to post code nicely on the forums: https://forum.unity.com/threads/using-code-tags-properly.143875/

    Okay, so I stopped reading your code after a moment, when I saw at least 1 main issue.
    In your coroutine, you are loop 10 times in one go. You should insert a "yield return null" inside the loop, to allow it to yield until the next frame.
    Right now you're doing 10 frames' worth of movement in 1 frame. :)

    Oh my.. now, I read the rest of your post before I hit submit. Okay.. I would suggest that you remove the code you have in Update(). Instead, at the end of each coroutine, add StartCoroutine(TheOtherRoutine());
    Replacing that, obviously, with the right method name ;)
    The reason for that, by the way, is that right now you're beginning a new coroutine every frame, despite the routine taking multiple frames to run... and it's not what you want =)
     
    Skalldyrssuppe and GroZZleR like this.