Nathan Radtke
Nathan Radtke

Reputation: 19

Unity3d if statements for triggers not working as expected

I'm making a 3d game and I want to have a counter add 1 for every trigger tile I walk over in a 2d top down sense. Example gameObject name is trigger1 and I have this trigger script on my player, when he walks onto the trigger it sets 2 ints(int1, int2) int 1 is the counter and int2 is just a flag so I know I am standing on the trigger1 tile. The way the script works now it will reset the counter almost every time I walk off one trigger to the next even tho the triggers are directly next to each other and my player is wide enough to not leave the trigger area entirely. I'm trying to figure out an if statement that would say if colliding with trigger1 int2 = 1 and when I'm not touching trigger 1 int2 = 0. then when int2 = 0 reset counter back to 0

example code

using UnityEngine;
using System.Collections;

public class TriggerScript : MonoBehaviour 
{
    public int in1 = 0;
    public int int2 = 0;
    void Start()
    {
        Debug.Log (int1);
    }

    void OnTriggerEnter (Collider trigger1)
    {
        int1++;
        Debug.Log ("trigger1 Enter");
        Debug.Log (int1);
    }

    void OnTriggerStay (Collider trigger1)
    {
        int2 = 1;
        Debug.Log ("trigger1 Stay");
    }

    void OnTriggerExit (Collider trigger1)
    {
        if (collider.gameObject.tag == "trigger1") {
            Debug.Log ("int2 = 1");
        } else {
            int2 = 0;
            Debug.Log ("int2 = 0");
        }
    }

    void Update (){
        if (int2 == 0)
            int1 = 0;
    }


}

Upvotes: 0

Views: 896

Answers (1)

Gunnar B.
Gunnar B.

Reputation: 2989

To put my comment into code:

public int score = 0;
public int triggerCounter = 0;

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.tag == "trigger1")
    {
        score++;
        triggerCounter++;
    }
}

void OnTriggerExit(Collider other)
{
    if(other.gameObject.tag == "trigger1")
    {
        triggerCounter--;
    }
}

void Update()
{
    if(triggerCounter <= 0)
    {
        score = 0;
        triggerCounter = 0;      // just for savety
    }
}

Upvotes: 1

Related Questions