简体   繁体   中英

Unity 3D Counting Number of Agent Passes through a door

I am trying to make fire evacuation simulation by using Unity. I need to count the number of agent passes through the exit door during the evacuation. Is there any way to do it?

You could set up a simple trigger collider system.

First, you would place a box collider at the exit door, and set it to trigger so it isn't a solid object (objects can path through it, rather than walk into it). Now, add a Rigidbody to this box collider, and set first drop-down menu that says 'Dynamic' to 'Kinematic'. Now, a way to count them. We will ad the following script to the box collider object:

using UnityEngine;

public class ExitDoor : MonoBehavour
{
   void OnTriggerEnter(Collider obj)
   {
       if (obj.gameObject.tag == “agent”)
       {
       }
   }
}

This doesn't work yet, because we don't have anything other than an OnTriggerEnter statement. OnTriggerEnter is called every time either a game object passes through a trigger collider or this game object passes through a trigger collider. We set up an if statement to detect if the game object that passed through it has a certain tag. We are searching for a tag called “agent”. Set each agent's tag to “agent”. Now we should start a counting system.

using UnityEngine;

public class ExitDoor : MonoBehavour
{
   public int agents;

   void OnTriggerEnter(Collider obj)
   {
       if (obj.gameObject.tag == “agent”)
       {
           agents += 1;
       }
   }
}

Now, we add 1 to a variable each time an agent enters the collider. The only problem with this is that if the agent goes through the collider twice, it will count it twice.

This system is done, but now you might want to access this from different scripts. We will use GetComponent<>() to access the script. Add this to your game management script, or whatever you want to be accessing this:

using UnityEngine;

public class GameManagement : MonoBehavour
{
   public GameObject ExitDoor;
   public int agents;

   void Update()
   {
      agents = ExitDoor.GetComponent<ExitDoor>().agents;
      if (agents == 10)
      {
         Debug.Log(“10 agents have exited.”);
      }
   }
}

Now, we access the script ExitDoor , and get agents from it. Make sure you set the ExitDoor variable from the game management script to the box collider game object used for counting.

This was untested and if you get any bugs or this wasn't what you wanted, comment on this post to ask me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM