Search Unity

OnTiggerEnter/OnTriggerExit is called twice

Discussion in 'Scripting' started by C30N9, Jan 19, 2014.

  1. C30N9

    C30N9

    Joined:
    Dec 11, 2013
    Posts:
    34
    I'm trying to increase an integer by 1 whenever the player collides with a trigger, but instead it increases by 2, which means the function is called twice. I put comments next to where I made necessary changes to get what I want. But I'm asking this for several purposes in the future. Here's the code:

    Code (csharp):
    1. var PortalActive : boolean = false;
    2.  
    3. static var PortalCount : float = 0; //Was originally int, but I changed it so it accepts 0.5
    4.  
    5. function Start () {
    6.     gameObject.renderer.material.color.a = 0.75f;
    7. }
    8.  
    9. function OnTriggerExit (collision : Collider) {
    10.  
    11.     if (collision.gameObject.FindWithTag ("Player")) {
    12.         if (!PortalActive) {
    13.             PortalActive = true;
    14.        
    15.             gameObject.renderer.material.color = Color (0, 1, 0, 0.75);
    16.             gameObject.particleSystem.startColor = Color.green;
    17.  
    18.             PortalCount += 0.5; //Was originally 1, but I changed it to 0.5 so I can get 1
    19.            
    20.         }
    21.     }
    22. }
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    for a start, change
    if (collision.gameObject.FindWithTag ("Player")) {
    to
    if (collision.gameObject.tag == "Player") {
    Doesn't make sense to perform a find operation when you already have a reference to the object

    Is there only one instance of this script?
     
  3. C30N9

    C30N9

    Joined:
    Dec 11, 2013
    Posts:
    34
    Whoops, it turns out that I added the script twice.

    Thanks for pointing that out.