Last active
December 27, 2019 06:41
-
-
Save cyberfox/9e3b9f846abf341a381941df0ef1940e to your computer and use it in GitHub Desktop.
Use tags to automatically add spawned GameObjects to the list of followers-of-the-leader.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Pathfinding; | |
using UnityEngine; | |
namespace BehaviorDesigner.Runtime.Tasks.Movement.AstarPathfindingProject | |
{ | |
[TaskDescription("Tagged GameObjects Follow the leader with the A* Pathfinding Project.")] | |
[TaskCategory("Movement/A* Pathfinding Project")] | |
[TaskIcon("Assets/Behavior Designer Movement/Editor/Icons/{SkinColor}LeaderFollowIcon.png")] | |
class TaggedLeaderFollow : LeaderFollow | |
{ | |
[Tooltip("Tag to generate a list of agents")] | |
public String agentTag; | |
public override TaskStatus OnUpdate() | |
{ | |
/** | |
* We're going to set up agents depending on tag, if a tag is present. | |
*/ | |
if (!string.IsNullOrEmpty(agentTag)) | |
{ | |
GameObject[] tagged = GameObject.FindGameObjectsWithTag(agentTag); | |
if (AnyNewAgents(tagged)) | |
{ | |
agents = new SharedGameObject[tagged.Length]; | |
for (int i = 0; i < tagged.Length; i++) | |
{ | |
agents[i] = tagged[i]; | |
} | |
aStarAgents = new IAstarAI[agents.Length]; | |
transforms = new Transform[agents.Length]; | |
// Set the speed and turning speed of all of the agents | |
for (int i = 0; i < agents.Length; ++i) | |
{ | |
aStarAgents[i] = agents[i].Value.GetComponent<IAstarAI>(); | |
transforms[i] = agents[i].Value.transform; | |
aStarAgents[i].maxSpeed = speed.Value; | |
} | |
} | |
} | |
return base.OnUpdate(); | |
} | |
private bool AnyNewAgents(GameObject[] tagged) | |
{ | |
// Short circuit the obvious and common case. | |
if (tagged.Length > agents.Length) return true; | |
bool hasAll = true; | |
HashSet<int> knownAgents = new HashSet<int>(); | |
foreach (var agent in agents) | |
{ | |
knownAgents.Add(agent.Value.GetInstanceID()); | |
} | |
foreach (var obj in tagged) | |
{ | |
hasAll = hasAll && knownAgents.Contains(obj.GetInstanceID()); | |
} | |
return !hasAll; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment