Search Unity

OnTriggerExit/OnTriggerEnter not working properly

Discussion in 'Scripting' started by Nemanja_DarkOne, Aug 21, 2014.

  1. Nemanja_DarkOne

    Nemanja_DarkOne

    Joined:
    Dec 11, 2013
    Posts:
    8
    Hello everyone I have been trying to solve this problem for couple of days but with no luck.

    Here is a setup. Game that I am doing is a match 3 type game. Board has Gems that are GameObjects and they all have Box Collider. Every gem has a tag "Gem" and every gem has 4 Detectors. One on tope bottom left and right. They also have Box Collider and a Script. This is the code of the Detectors Script.

    Code (CSharp):
    1. public Gem owner;
    2.  
    3. void OnTriggerEnter(Collider c)
    4. {
    5.     if(c.tag == "Gem")
    6.     {
    7.     owner.AddNeighbor(c.GetComponent<Gem>());
    8.     }
    9. }
    10.  
    11. void OnTriggerExit(Collider c)
    12. {
    13.     if(c.tag == "Gem")
    14.     {
    15.     owner.RemoveNeighbor(c.GetComponent<Gem>());
    16.     }
    17. }
    And a code from Gem script

    Code (CSharp):
    1. public void AddNeighbor(Gem g)
    2. {
    3.     if(!Neighbors.Contains(g))
    4.                    {
    5.              Neighbors.Add(g);
    6.     }
    7. }
    8. public void RemoveNeighbor(Gem g)
    9. {
    10.     Neighbors.Remove(g);
    11. }
    12.  
    And now the problem.

    When I start moving and matching gems some of the gems do not get their neighbors right. For example I match first 3 gems on Y axes and they are destroyed from top come falling 3 new gems. Gem that falls on the 4th gem on Y axes does not add the 4th gem as his neighbor and the 4th gem does not add 3rd gem as his neighbor. The other problem is that when I move gem sometimes he does not remove his old neighbor but just add new one then I have some weird matches because I am checking through the neighbor list to see potential matches. When the Board is created all gems have there neighbors properly detected.
     
  2. hariavm

    hariavm

    Joined:
    Aug 18, 2014
    Posts:
    73
    make a debug on Trigger Funtions First
     
  3. Nemanja_DarkOne

    Nemanja_DarkOne

    Joined:
    Dec 11, 2013
    Posts:
    8
    I figured it out. Problem was not in the script but in the models. Box collider was too large so sometimes the Gem could not detect that he has left his neighbor so I scaled collider down and now it all works.

    Thank you hariavm for you answer
     
  4. hariavm

    hariavm

    Joined:
    Aug 18, 2014
    Posts:
    73
    u are welcome!!!!!1