unity – Coroutine problem, I don’t know what’s happening

Calling function.

 private const int deathHangTime = 2;   
 private void Die()
    {
          Debug.Log("1 " + Time.time);
          StartCoroutine(DelayForTime(deathHangTime));
          Debug.Log("4 " + Time.time);
    }

Coroutine

IEnumerator DelayForTime(float time)
{
     Debug.Log("2 " + Time.time);
     yield return new WaitForSeconds(time);
     Debug.Log("3 " + Time.time);
}

enter image description here

Why doesn’t it wait for 2 seconds?
Why doesn’t it print the 3rd Debug line?

unity – Coroutine different behaviour when called from another script

I am quite new with game dev, specially with unity. In order to understand how it works, I decided to start small with a pong game.

I have a Ball script, which in the Update() method move the ball depending to the speed, and if a player score, it increment a score field and reset the ball to the center (and stop the ball for 2 seconds) trough a coroutine function.

Ball script:

public class Ball : MonoBehaviour
{
    (SerializeField)
    float speed;
    int isMoving = 1;
    float radius;
    Vector2 direction;
    Vector2 startPosition;

    // Start is called before the first frame update
    void Start()
    {
        direction = Vector2.one.normalized;
        radius = transform.localScale.x / 2; // half the width
        startPosition = new Vector2(transform.position.x, transform.position.y);
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(direction * speed * isMoving * Time.deltaTime);

        if (transform.position.y < GameManager.bottomLeft.y + radius && direction.y < 0) {
            direction.y = -direction.y;
        } 
        if (transform.position.y > GameManager.topRight.y - radius && direction.y > 0) {
            direction.y = -direction.y;
        }

        // Ball go in any goal
        if (transform.position.x < GameManager.bottomLeft.x + radius && direction.x < 0) {
            GameManager.instance.addScorePlayer("p2");
            StartCoroutine( Reset() );
        } 
        if (transform.position.x > GameManager.topRight.x - radius && direction.x > 0) {
            GameManager.instance.addScorePlayer("p1");
            StartCoroutine( Reset() );
        }
    }

    IEnumerator Reset() {
        isMoving = 0;
        transform.position = startPosition;

        yield return new WaitForSeconds(2);

        isMoving = 1;
    }
}

This works as expected! The score is incremented, the ball go back to the center, wait for 2 seconds and start to move again.
However, now I want to call the Ball Reset() method trough my GameManager (because I want to code some logics inside the GameManager).

So here are my modifications:

Ball script: (remove Reset() calls and update Reset() method to public)

public class Ball : MonoBehaviour
{
    ...

    // Update is called once per frame
    void Update()
    {
        ...

        // Ball go in any goal
        if (transform.position.x < GameManager.bottomLeft.x + radius && direction.x < 0) {
            GameManager.instance.addScorePlayer("p2");
        } 
        if (transform.position.x > GameManager.topRight.x - radius && direction.x > 0) {
            GameManager.instance.addScorePlayer("p1");
        }
    }

    public IEnumerator Reset() {
        isMoving = 0;
        transform.position = startPosition;

        yield return new WaitForSeconds(2);

        isMoving = 1;
    }

GameManager script:

public class GameManager : MonoBehaviour
{

    public Ball ball;

    ...

    void Start()
    {   
        ...

        // Create ball
        Instantiate (ball);

    }

    public void addScorePlayer(string player) {

        if (player == "p1") {
            score1 += 1;
            score1Text.text = score1.ToString();
        }
        else if (player == "p2") {
            score2 += 1;
            score2Text.text = score2.ToString();
        }

        StartCoroutine( ball.Reset() );
    }

This doesn’t work for some reason. The ball don’t come back to the center, and the score increment infinitely.

I have tried many things and I have figured out that the behaviour is the same as running the Reset() method trough the Ball script without the StartCoroutine.

So it seems that the Coroutine don’t work properly if called trough the GameManager ?
I have also printed some logs into my console in the Ball.Reset() method, and the method is being called, so I don’t understand why the ball don’t go back to the center.

(Link to my public github repository https://github.com/Sewake/Unity2D-Pong)

android – I’m unable to make databinding changes in catch block inside a coroutine. Why?

During my splash activity I’d like my app to ping the server and perform a few quick checks. If this fails, I’d like to display an option to try again, or continue without internet. Here’s some basic initialization:

private lateinit var binding: ActivitySplashBinding
private val response = MutableLiveData<String>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    // enable databinding with layout files
    binding = DataBindingUtil.setContentView(this, R.layout.activity_splash)
    response.value = "Initializing ..."
    response.observe(this, Observer {
        binding.statusText.text = it
    })
    // set up button click listeners here too, omitted for brevity
    checkInternet()

}

Setting some TextView values in onCreate works fine, so I know data binding is working.

private var job = Job()
private val checkScope = CoroutineScope(job + Dispatchers.IO)

private fun checkInternet() {
    binding.apply {
        buttonTryAgain.visibility = View.GONE
        buttonContinue.visibility = View.GONE
    }
    response.postValue("Checking internet connection...")
    checkScope.async {
        try {
            myApi.retrofitService.getFoo() // this is synchronous
            startNextActivity()
        } catch (e: Exception) {
            Log.i(TAG, "Start exception block")
            response.postValue("Hm, it seems we're unable to reach the server. Check your internet connection?")
            binding.apply {
                buttonTryAgain.visibility = View.VISIBLE
                buttonContinue.visibility = View.VISIBLE
            }
            Log.i(TAG, "We never reach here, why?")
        }
    }
}

I test by putting the device into airplane mode, and the call to binding.apply in the catch block never completes. Why? Also, assuming there’s a exception here (and async doesn’t rethrow exceptions), how can I see it?

unit: why can I still call a coroutine from another script, even though I marked it private?

I have this private coroutine in my WinDialogue script:

private IEnumerator ActivateStars(int count)
{
    for (var index = 0; index < count; index++)
    {
        _stars(index).SetActive(true);
        yield return new WaitForSeconds(.3f);
    }
}

And somehow I can still call it from my UIManager script:

_winDialogue.GetComponent().StartCoroutine("ActivateStars", starCount);

How can that be if I marked it private?

Am I wrapping the synchronous code in ktor / Kotlin coroutine correctly?

I am playing with ktor right now. If I understand this correctly, the code in the ktor drivers should be as asynchronous as possible. So I was trying to figure out how to write the synchronous code (potentially expensive) in a Kotlin routine. This is what I have written:

    install(DefaultHeaders)
    install(CallLogging) {
        level = Level.INFO
    }
    install(Routing) {
       // More routes here

        get("/hello") {
            val key = async {
                // Emulating an expensive synchronous call by doing lots of calculations
                log.info("Calculating key")
                var sb = StringBuilder(32)
                for (i in 0..15) {
                    var sym: Byte = (Math.random() * 255).toByte()
                    for(j in 1..10000000) {
                        sym = (sym + Math.random() * 40).toByte()
                    }
                    sb.append(String.format("%02X", sym))
                }

                log.info("Ended key calc")

                sb.toString()
            }

            call.respondText("Hello again! Your key is ${key.await()}", ContentType.Text.Plain)
        }
    }
}

I'm wrapping my potentially expensive synchronous code in async get a Deferred and so await that.

I think it works because I can make a simultaneous request to / hello and other routes.

Is this the right way to do it? Should I bother or can I write synchronous code on the ktor controllers? Thank you.

unit – Coroutine running only partially

I have a Corutina that I use to throw and generate an enemy in my game. This routine works perfectly well, with the exception of the first call. I'm pretty sure this is because I'm probably carrying something before it's ready, but I don't know enough to know where.

This is my code (note the Debug.Log entries). I have deleted what I think is irrelevant code.

  1. EnemyHandler.cs

    public class EnemyHandler : MonoBehaviour
    {
    public int mob_id;
    IEnumerator LoadMob()
    {
        Debug.Log("Checkpoint 1");
    
        WWWForm form = new WWWForm();
        form.AddField("mob_id",mob_id);
        WWW www = new WWW("my-url-here",form);
        yield return www;
        Debug.Log("@@@@@@ Checkpoint 2 @@@@@@");
        string() webResults = www.text.Split('t');
    
        int returncode = int.Parse(webResults(0));
    
        switch (returncode)
        {
            case 0:
            //Mob Loaded Successfully
            //Mob variables are set here
            Debug.Log("@@@@@@ Checkpoint 3 @@@@@@");
            break;
    
            default:
            Debug.Log("Error!");
            break;
        }
    
    }
    
     public void CallMobLoad(int requested_mob_id)
     {
         mob_id = requested_mob_id;
         StartCoroutine(LoadMob());
         Debug.Log("Coroutine called! Checkpoint 0");
     }
    }
    

2.GameManager.cs (This is my main class)

public class GameManager : MonoBehaviour
{
    public GameObject spawnManager;
    public static EnemyHandler thisenemy;

    void Start()
    {
     thisenemy = spawnManager.AddComponent();
     thisenemy.CallMobLoad(1);
    }
}

CallMobLoad is called once at the beginning, and every time a monster dies. It never works when Start () is invoked, but it always works after that.

In addition, the first call only calls the first 2 Debug.Logs "Control Point 0" and "Control Point 1", none of the other control points are affected. Each subsequent call works correctly and reaches all control points.

I really want to learn how / why this happens, any help is greatly appreciated!

python – TypeError: the object & # 39; coroutine & # 39; is not invoked

ERRO:

TypeError: the object & # 39; coroutine & # 39; is not invoked
The view function did not return a valid response. The return type must be a string, tuple, response instance or WSGI invoked, but it was a routine.

Code:

await send_message.welcome()
return render_template("preview.html")

unit – Is it possible to use a coroutine and GetAxis to rotate a game object?

For the sake of learning about the coroutine, I want to turn the following into a cleaner To update That just calls a coroutina. It's possible?

using UnityEngine;

Public class driver: MonoBehaviour
{
public flotation speed = 5f;
private floating deltaX;

void Home ()
{
deltaX = transform.localEulerAngles.x;
}
Null update ()
{
deltaX + = Input.GetAxis ("Vertical") * speed;
deltaX = Mathf.Clamp (deltaX, -90f, 90f);
transform.localEulerAngles = new Vector3 (deltaX, transform.localEulerAngles.y, transform.localEulerAngles.z);
}
}

unit – Why releasing a key pressed "f" does not prevent the coroutine from turning?

I am learning Unity and what follows is my simplification of the code presented in Coroutines.

My expectation is that the Fade() it simply rotates in a very short period of time because the GetKeyDown ("f") is true only in the transition from "unpressed" to "pressured" states.

However, in the following code, Fade() rotate from f = 0 to f = 999 continuously (without stopping at once) instead of, for example, from f = 0 to f = 100 on the first key and from f = 101
to f = 159 on the second key press, etc.

IEnumerator Fade ()
{
for (int f = 0; f <1000; f ++)
{
Debug.Log ($ "{f}");
zero performance;
}
}

Null update ()
{
if (Input.GetKeyDown ("f"))
{
StartCoroutine ("Fade");
}
}

What causes this unexpected result and how to solve it?

unity – Coroutine constantly updating the animator transition

I have a problem for a while and I'm running out of ideas:
I've made a coroutine used to implement animations in attacks, something like this

I Private enumerator FirstAttack ()
{

comboCounter = 1;
myAnimator.SetInteger ("comboSequence", comboCounter);
currentState = PlayerState.attack;
zero performance;

performance return new WaitForSeconds (AttackTemplate.SetDuration (0.9f));
comboCounter = 0;
myAnimator.SetInteger ("comboSequence", comboCounter);

currentState = PlayerState.walk;

}

This corutina works perfectly well. The problem occurs when I try to concatenate this with another coroutine to perform something like a combo sequence; to do so, I basically add a cycle of time that checks if I'm pressing the attack button while there is a period of time open for the second attack to connect. The result is this:

I Private enumerator FirstAttack () {

comboCounter = 1;

myAnimator.SetInteger ("comboSequence", comboCounter);

currentState = PlayerState.attack;
performance returns the new WaitForSeconds (AttackTemplate.SetDuration (0.6f) - comboTimer); // Problem: if I reduce the time below the animation time of the second animation, the second animation will not go to the end

StartCoroutine (IntervalCounter ());
comboCounter = 0;
myAnimator.SetInteger ("comboSequence", comboCounter);
currentState = PlayerState.walk;

}

I Private SecondAttack enumerator ()
{

comboCounter = 2;
myAnimator.SetInteger ("comboSequence", comboCounter);
currentState = PlayerState.attack;
zero performance;

performance return new WaitForSeconds (AttackTemplate.SetDuration (0.9f));
comboCounter = 0;
myAnimator.SetInteger ("comboSequence", comboCounter);

currentState = PlayerState.walk;

}


Private IEnumerator IntervalCounter ()
{
comboTimer = AttackTemplate.SetComboTimer (0.4f);
while (comboTimer> = 0)
{
Debug.Log (comboTimer);
comboTimer - = Time.deltaTime;
if (Input.GetKeyDown (KeyCode.Mouse0))
{
Debug.Log ("Chained");
StartCoroutine (SecondAttack ());
performance break
}
zero performance;
}

}

My problem is that, after adding the while loop, the transition to the first animation is still updated, to be more accurate than what is happening. Any state to Basic attack tree In the next image.

enter the description of the image here

If I press the attack button, this transition will be repeated as long as the routine works. I tried to wrap the first two lines in which I configured the animator so that it would not do anything if the integer administered the combo sequence. comboCounter is already set to 1 (which is the value related to the first attack), like this

                                yes (comboCounter! = 1)
{
comboCounter = 1;
myAnimator.SetInteger ("comboSequence", comboCounter);
} else if (comboCounter == 1) {

}

But it keeps repeating itself. I wanted to use something like WaitUntil, but I just tried to put it and have an always false error, in order to suspend the routine indefinitely, but in that period keep updating the animator. Do you have any idea why that is? How do I prevent a coroutine from running all the time?