• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
4
Question by TRON-dll · Jul 02, 2014 at 12:09 AM · c#triggerontriggerenter

OnTriggerEnter being called multiple times in succession?

Hey all,

Basically, I have a box that the player has to be able to collect. When the player "collects" it, the box will actually just instantly move to another spawnpoint, and I'll also execute scoring stuff. When the player object passes over a box, OnTriggerEnter(Collider hitObject) is called, and I do a check to make sure that the object I hit is actually a box that can be collected. If it is, I move the box to a different location to give the effect

The problem is that when my player object hits the box, OnTriggerEnter is called two or three times, which will undoubtedly cause issues for keeping track of the score. It's my understanding that OnTriggerEnter is called once upon the initial collision with the object, so I'm not sure why it's being called multiple times per collision.

Some of my code follows:

 //From the player object's script
 
 void OnTriggerEnter (Collider hitObject)
     {    
         if (hitObject.tag == "peep")
         {
             hitObject.transform.position = new Vector3(0,-100,0);
             Debug.Log("Collected");
             hitObject.transform.GetComponent<peepControl>().collect();
         }
     }
 
 //From the peepControl script
 
 public void collect()
     {
         int i = Random.Range(0,allSpawns.Length);
         while (allSpawns[i] == currentSpawn)
             i = Random.Range(0,allSpawns.Length);
         
         transform.position = allSpawns[i].transform.position;
         currentSpawn = allSpawns[i];
     }

Through Debug.Log I found that the OnTriggerEnter function was testing true on its if statement three times before the object actually moved at all. Suggestions?

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image kromenak · Jul 02, 2014 at 12:23 AM 0
Share

Do you have multiple colliders on your player object? If so, OnTriggerEnter might get called for each collider separately?

5 Replies

· Add your reply
  • Sort: 
avatar image
20
Best Answer

Answer by fafase · Jul 02, 2014 at 12:36 AM

Is the collider on your player a Character Controller or a sphere collider or a capsule collider? Those being circular may have two (or more) contact points.

Just use a boolean to prevent multiple calls.

 void OnTriggerEnter (Collider hitObject)
 {
     if(isColliding) return;
     isColliding = true;
     // Rest of the code
 }
 
 void Update(){
     isColliding = false;
 }

Even though your collider is not one of those I mentioned, this should work. If the boolean is true, quit the method, else set it to true and do the rest.

Since Physics is done all at once and before update in the same frame, if you have a second collision detected, nothing will happen since the first already set the boolean.

Update is just putting it back to false.

EDIT: In order to remove the update, one can also do as such:

 void OnTriggerEnter (Collider hitObject)
 {
     if(isColliding) return;
     isColliding = true;
     // Rest of the code
     StartCoroutine(Reset());
 }

 IEnumerator Reset()
 {
      yield return new WaitForEndOfFrame();
      isColliding = false;
 }
Comment
Add comment · Show 11 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image TRON-dll · Jul 02, 2014 at 08:07 AM 0
Share

$$anonymous$$y player object is just using a cube collider, but I get your idea and I was actually thinking of doing something similar. I just felt like maybe there was a function I didn't know about that could achieve the same effect more efficiently, so I might wait for a few other suggestions before marking this one as the answer.

Thanks!

avatar image TruffelsAndOranges · Jul 21, 2015 at 04:35 PM 0
Share

I get this problem with a 2D box trigger collider colliding with another 2D box collider.

avatar image fafase · Jul 24, 2015 at 06:05 PM 0
Share

squares also can have 2 contacts points, just use the same process.

avatar image Siraaaj-Ahmed · Dec 28, 2016 at 10:59 PM 0
Share

O$$anonymous$$G thank you!! thought I was going crazy, capsule collider was the issue for me.

avatar image aloften · Aug 30, 2017 at 02:11 AM 0
Share

I cant find this in the docs anywhere and it doesnt show up in the suggested codes in mono. Im thinking this is old....is there a newer version?? I cant seem to find one.

avatar image fafase aloften · Sep 01, 2017 at 05:28 AM 0
Share

you mean this ? https://docs.unity3d.com/ScriptReference/$$anonymous$$onoBehaviour.OnTriggerEnter.html

Show more comments
avatar image
3

Answer by DRsabadash · Mar 17, 2017 at 08:01 AM

For some reason, setting a boolean check for colliders can sometimes cause the boolean value to either flip, or to turn on/off the OnTriggerEnter/OnTriggerExit methods while remaining in the trigger area, like opening a door and closing it repeatedly while in the trigger area, or flipping the boolean value so it closes when you approach and opens when you walk away.

using a simple variable iterator prevents the actual method from being called repeatedly, guaranteeing only one execution per collision.

 //previous code in class
 //using a door opening and closing as an example
 [SerializeField] private GameObject device;
     private int i = 0;
 
 
     void OnTriggerEnter(Collider other){
         DoorScript door = device.GetComponent<DoorScript>();
         if (i == 0) {
             if (door != null) {
                 door.Operate ();
                 i++;
             }
         }
 
     }
     void OnTriggerExit(Collider other){
         DoorScript door = device.GetComponent<DoorScript>();
         if (i == 1) {
             if (door != null) {
                 door.Operate ();
                 i = 0;
             }
         }
 
     }
 /* All DoorScript contains is a function Operate() and a boolean for if the door is open, and an if/else statement in Operate() for moving door to open if bool is false (set to closed) and moving door to closed if bool is true (set to open)

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
2

Answer by sisse008 · Mar 25, 2018 at 10:52 AM

ontriggerenter should be on each "collectible" object. not on the player:

 class Target
 {
         private collected = false;
         void collect() {
           ....
           collected = true;
          }
        void OnTriggerEnter (Collider other)
        {   
            if (!collected && other.tag == "player")
            {
                transform.position = new Vector3(0,-100,0);
                Debug.Log(gameObject.name +" was Collected");
                collect();
          }
      }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SchafiSchafoesselchen · May 06, 2018 at 12:00 AM 0
Share

Why should it be on the object not the player?

avatar image
2

Answer by shawnsi · Mar 28, 2019 at 03:18 PM

I know this is an old topic, but I wanted to share another solution just in case. I solved this issue by setting character Rigidbody's IsKinematic to "true". My guess is that when IsKinematic is false, the colliders would push the character back enough to trigger OnTriggerExist. This caused a trigger loop and caused it to run OnTriggerEnter and OnTriggerExit multiple times.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image jonylu7 · Feb 14, 2020 at 01:39 PM 0
Share

Your Solution works for me,thanks a lot !

avatar image
1

Answer by MrSpiky · Feb 14, 2020 at 10:34 AM

Having multiple colliders on your object can cause this to happen aswell Ik old topic...

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Collision problem in C# 4 Answers

C# - Problem with trigger that won't activate 1 Answer

OnTriggerEnter doesnt see enemy 1 Answer

Checking Tag of Trigger Prefab 1 Answer

Application.LoadLevel ("lower") loads on start-up, not when triggered; Deadline is soon HELP! 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges