S
S
SkyCrusher2018-11-02 13:31:58
C++ / C#
SkyCrusher, 2018-11-02 13:31:58

Why is this code only executed once?

The crux of the problem is this. I want to file a simple animation (rotate 180 x) for the mute button. And when I launch it and click on it for the first time, the animation plays, the sprite changes, the component turns off. In a word, everything works. But further - does not react at all to pressing. Please explain what is wrong.
Tried: stop coroutines(StopCoroutine(RotateMe(new Vector3(180, 0, 0), 0.5f)))); wrote StopAllCoroutines() both in the condition and in the body of the coroutine; split the condition into two different scripts. Obviously no results...

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

public class SoundButtonOff : MonoBehaviour
{
    public GameObject Audio;
    public bool SoundOff = false;

    public Sprite SpriteSoundOff;
    public Sprite SpriteSoundOn;

    private void Start()
    {
        GetComponent<Image>().sprite = SpriteSoundOff;
    }

    public void OnClickSound()
    {
        if (!SoundOff)
        {
            Audio.GetComponent<AudioListener>().enabled = true;
            StartCoroutine(RotateMe(new Vector3(180, 0, 0), 0.5f));
            GetComponent<Image>().sprite = SpriteSoundOn;
            SoundOff = true;
        }
        else if (SoundOff)
        {
            Audio.GetComponent<AudioListener>().enabled = false;
            StartCoroutine(RotateMe(new Vector3(180, 0, 0), 0.5f));
            GetComponent<Image>().sprite = SpriteSoundOff;
            SoundOff = false;
        }
    }

    IEnumerator RotateMe(Vector3 byAngles, float inTime)
    {
        var fromAngle = transform.rotation;
        var toAngle = Quaternion.Euler(transform.eulerAngles + byAngles);
        for (var t = 0f; t < 1; t += Time.deltaTime / inTime)
        {
            transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t);
            yield return null;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yuuki Wesp, 2018-11-04
@SkyCrusher

Little information about the script.
What object is it on?
Where is the OnClickSound function called?
I see that this is a new UI.
In the button through the editor, you need to specify the action (button component, On Click list)
If it is not a button, you need to implement the IPointerClickHandler interface if it is just an Image and handle the click in the OnPointerClick function.

K
koito_tyan, 2018-11-02
@koito_tyan

just try to fasten private void Update() { } for the test

A
abramovskih, 2018-11-03
@abramovskih

Audio.GetComponent().enabled = false; Disables the listener! Stops responding to pressure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question