unity-game-enginetriggers

How would I get the info of a particular type of objects in a particular trigger in Unity3d


I want to change a thing based on the number of players of each teams in a trigger.

I'm thinking of getting the info of all the objects in the trigger access their tags and identify how many players of each teams are present in that trigger. But I can't find anything to do this.


Solution

  • Init team counts as 0:

    int team1 = 0;
    int team2 = 0;
    

    Increase/decrease team count on trigger callbacks. Here you can use tags or whatever you prefer. I recommend having the team information in a script:

    void OnTriggerEnter(Collider other)
    {
        Player player = other.gameObject.GetComponent<Player>();
        if(player == null) return;
        if(player.team == 1) team1++;
        else team2++;
    }
    
    void OnTriggerExit(Collider other)
    {
        Player player = other.gameObject.GetComponent<Player>();
        if(player == null) return;
        if(player.team == 1) team1--;
        else team2--;
    }
    

    And lastly, do what you want with your team counts:

    void Update()
    {
        //use team1 and team2 the way you want
    }