0
\$\begingroup\$

OK so I have used the Unity Event Trigger many times to check for on-screen button presses for Android games. One example I have made many times is a left and right arrow button, which moves the character. There is OnPointerDown() and OnPointerUp() methods which i am utilising (or trying to at least!).

So I have a bool called isLeftToggled and its initialised as 'false'. OnPointerDown/Up both link to a method called ToggleButtonLeft():

    public void ToggleButtonLeft(){
    Debug.Log ("LEFT TOGGLED" + isLeftToggled);

    if (isLeftToggled)
    {
        isLeftToggled = false;
    }
    else 
    {
        isLeftToggled = true;
    }
}

That Debug.Log above reads out ok, it toggles between true and false (although puzzlingly the first log i get is 'True').

However in my update method I have it constantly inform me if its true or false, and it is false for every single call.

I verified this because the ship (game character) doesnt turn when I try to use the bool to turn it. If I initialise the bool to 'true' and remove the toggle by comments, the ship turns fine.

I have the Event Trigger on the button game object, I didnt remember if I had to add something else to make it work. But I am fairly sure the button is working, because it always prints the Debug.Log thats inside the method being called by the two buttons.

Any ideas why the bool is 'false' for every frame. Shouldn't my code above toggle it to true whilst the finger is held on the button?

Here is the whole class (nb. i thought about trimming out the irrelevant parts but didnt want to miss something important out so decided to post whole thing):

public class Player : MonoBehaviour {
float rotationSpeed = 360f;
float currentThrust = 0f;
float thrustDecay = 0.02f;
float accel = 0.25f;
float maxThrust = 150f;

float thrustAngle, prevThrustAngle;
float maxTurningThrust;
public GameObject laserStartPoint;
float laserFireRate = 0.5f;
private float laserFireTimer = 5f; // the 5 is a random amount just to make sure no delay at the beginning

public GameObject laserPrefab;

private List<GameObject> lasers = new List<GameObject>();

private Collider gameArea;

private GameObject afterburner;
public GameObject explosionPrefab;

AudioSource audioSource;
public AudioClip laserSound, deathSound, deathExplosionSound, thrusterSound;
float deathWaitTimeBeforeDestroy = 2f;
bool isDying;
GameObject shipModel;

private bool isLeftToggled = false, isRightToggled;

void Start () {
    isDying = false;
    gameArea = GameObject.FindGameObjectWithTag("GameArea").GetComponent<Collider>();
    maxTurningThrust = maxThrust * 0.012f;
    afterburner = GameObject.FindGameObjectWithTag("Afterburner");
    afterburner.SetActive(false);
    audioSource = GetComponent<AudioSource>();
    shipModel = GameObject.FindGameObjectWithTag("ShipModel");
}

void Update () {
    if (isDying)
    {
        shipModel.SetActive(false);
        deathWaitTimeBeforeDestroy -= Time.deltaTime;
        if (deathWaitTimeBeforeDestroy <= 0)
        {
            Destroy(this.gameObject);
            GameController.instanceOf.PlayerLoseLife ();
        }
    }
    else
    {
        HandleInput();
        CheckScreenBounds();

        laserFireTimer += Time.deltaTime;
    }

    Debug.Log("is left toggled: " + isLeftToggled);
}

void HandleInput(){
    // activate weapon
    if (Input.GetKey(KeyCode.Space))
    {
        FireWeapon();
    }
    // Rotate left
    if (Input.GetKey(KeyCode.A) || isLeftToggled)
    {

        transform.Rotate(0, -rotationSpeed * Time.deltaTime, 0);
    }
    // Rotate right
    if (Input.GetKey(KeyCode.D))
    {
        transform.Rotate(0, rotationSpeed * Time.deltaTime, 0);
    }
    // activate thrusters
    if (Input.GetKey(KeyCode.W))
    {
        //audioSource.clip = thrusterSound;
        audioSource.PlayOneShot(thrusterSound, 0.25f);
        afterburner.SetActive(true);
        prevThrustAngle = thrustAngle;
        thrustAngle = transform.eulerAngles.y;
        if (currentThrust < maxThrust)
        {
            if (prevThrustAngle != thrustAngle)
            {
                if (currentThrust > maxTurningThrust) {
                    currentThrust = maxTurningThrust;
                }
            }
            currentThrust += accel;
        }
    }
    else
    {
        afterburner.SetActive(false);
        if (currentThrust > 0f)
        {
            currentThrust -= thrustDecay;
        }
    }


    // Move the ship in the direction it was facing at point when thruster button was last pressed
    transform.position += new Vector3(Mathf.Sin(thrustAngle * Mathf.Deg2Rad), 0, Mathf.Cos(thrustAngle * Mathf.Deg2Rad)) * currentThrust * Time.deltaTime;

    if (currentThrust < 0f)
    {
        currentThrust = 0f;
    }

}

void CheckScreenBounds()
{
    if (transform.position.x - (GetComponent<Collider>().bounds.size.x / 2) > gameArea.bounds.size.x / 2)
    {
        transform.position = new Vector3(-gameArea.bounds.size.x / 2, transform.position.y, transform.position.z);
    }
    if (transform.position.x + (GetComponent<Collider>().bounds.size.x / 2) < -gameArea.bounds.size.x / 2)
    {
        transform.position = new Vector3(gameArea.bounds.size.x / 2, transform.position.y, transform.position.z);
    }
    if (transform.position.z - (GetComponent<Collider>().bounds.size.z / 2) > gameArea.bounds.size.z / 2)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y, -gameArea.bounds.size.z / 2);
    }
    if (transform.position.z + (GetComponent<Collider>().bounds.size.z / 2) < -gameArea.bounds.size.z / 2)
    {
        transform.position = new Vector3(transform.position.x, transform.position.y, gameArea.bounds.size.z / 2);
    }
}

void FireWeapon()
{
    if (laserFireTimer >= laserFireRate)
    {
        GameObject tempLaser = laserPrefab;

        tempLaser.transform.position = laserStartPoint.transform.position;
        tempLaser.transform.rotation = laserStartPoint.transform.rotation;
        Instantiate(tempLaser);

        lasers.Add(tempLaser);

        laserFireTimer = 0f;
        tempLaser = null;


        audioSource.PlayOneShot(laserSound);
    }

}

public void Die()
{
    GameObject explosion = GameObject.Instantiate(explosionPrefab);
    explosion.transform.position = transform.position;
    audioSource.PlayOneShot(deathSound);
    audioSource.PlayOneShot(deathExplosionSound);
    isDying = true;
}

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Asteroid" || other.tag == "Saucer" || other.tag == "LaserEnemy")
    {
        Die();         
    }
}


public void ToggleButtonLeft(){
    Debug.Log ("LEFT TOGGLED" + isLeftToggled);

    if (isLeftToggled)
    {
        isLeftToggled = false;
    }
    else 
    {
        isLeftToggled = true;
    }
}
public void ToggleButtonRight()
{
    Debug.Log("RIGHT TOGGLED");

    if (!isLeftToggled)
        isRightToggled = true;
    else
        isRightToggled = false;
}

}

here is screenshot of unity. I think it sums up the problem quite well, the Event Trigger on the right shows its calling the method in the class I posted above, the log even shows its getting toggled to True when i push the button, but the ship doesnt rotate, and as you see in the log the bool is 'false' on every frame:

unity screen

\$\endgroup\$
  • 1
    \$\begingroup\$ "isLeftToggled" is likely an instance variable, and you're liking executing ToggleButtonLeft on a different instance than the one you're logging. Post the definition of the class including the declaration of isButtonLeft and the code where you log the value. \$\endgroup\$ – Josh Nov 15 '17 at 3:05
  • \$\begingroup\$ @JoshPetrie Sure I will grab it now and adjust my question . thanks for looking pal \$\endgroup\$ – Big T Larrity Nov 15 '17 at 3:07
  • 1
    \$\begingroup\$ Also if it fixes itself when you remove code, be sure you didn't write if (isLeftToggled = false) \$\endgroup\$ – Jay Nov 15 '17 at 3:11
  • \$\begingroup\$ @JoshPetrie thanks again Josh. ive posted the class now, hope its not too long to see the part you mean \$\endgroup\$ – Big T Larrity Nov 15 '17 at 3:12
  • 1
    \$\begingroup\$ I don't see the "update method that constantly informs you" of anything about isLeftToggled? I see Update() calling HandleInput() which rotates something if isLeftToggled is true, but that could easily be misread. \$\endgroup\$ – Josh Nov 15 '17 at 3:17
0
\$\begingroup\$

the answer is that, as JoshPetrie mentioned above, isLeftToggled is an instanced variable. But I am currently creating a new instance of the Player every time it dies. The problem with this is that the Event Trigger on my UI cannot cope with that. It was calling the method in the script (thats why i got the log telling me it was toggling), but of course it couldnt change the variable of the players isLeftToggled bool, because it has never been pointed to it.

The only fix I can think of for this, is to have the Player instanced in the Hierarchy of Unity, so that I can drag that into the Event Trigger. And I'll have to change my code to always use the same instance of the Player.

Unless there is a way to dynamically change the Event Trigger to tell it which Player I need it to connect with (??!?!?)

Anyway, I am past the problem at least. So thanks for those who helped me. Cheers

EDIT: Thanks to the kind help of LegendBacon on the Unity website, he has linked me to this solution for changing the event trigger during runtime: Unity Answers - full answer

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.