I’ve written a flocking behavior script, and I feel that I’m writing some clunky code, and I’d like some advice on how better to organize this code.
I’m what you’d call an “advanced beginner” at coding, and am trying to be more effective, efficient, and organized.
So, in my manager script is the following code particle, where I’m creating the manager script and creating an instance as a static variable to be referred to.
[System.NonSerializedAttribute]
public List<GameObject> boids;
void Awake(){
Instance = this;
boids = new List<GameObject>();
}
then I have the manager doing a FindAllObjectsWithTag() to build the List<>
void Start () {
populateList ();
for (int i = 0; i < boids.Count; i ++){
GameObject boid;
boid = boids[i];
boid.BroadcastMessage("setLocalArray");
}
}
void Update () {
compareVars();
}
void populateList(){
GameObject[] allFollowers;
allFollowers = GameObject.FindGameObjectsWithTag("follower");
foreach(GameObject follower in allFollowers){
boids.Add (follower);
}
print ("length of boids is " + boids.Count);
}
And finally, I have a compareVars() function in the update loop that checks the manager’s variables and passes them on to the individual boids if they have changed.
This is the part that I feel is really clunky, and it seems like there must be a better way to broadcast variables to individual flock members. There is a function on each boid, setLocalArray(), that references this manager’s variables and updates themselves.
void compareVars(){
if(separateWeight != separateCompare || seekWeight != seekCompare || wanderWeight != wanderCompare || cohesionWeight != cohesionCompare){
for(int i = 0; i < boids.Count; i ++){
boids[i].BroadcastMessage("setLocalArray");
}
separateCompare = separateWeight;
seekCompare = seekWeight;
wanderCompare = wanderWeight;
cohesionCompare = cohesionWeight;
}
}
So, my question is, are there better ways of doing this? I stumbled on this solution just seeking around and doing tutorials, and I’ve crunched it together in the only way I know how to do. What could I do better?
Thanks in advance for the advice