Creating A Basic Path For Enemies

I am unsure of how to achieve this in UnityScript:

1.Save all GameObjects with tag ‘way’ to an array

2.Sort the array alphabetically

3.Each ‘way’ object contains 4 GameObjects saved to variables named : ‘path1’ ‘path2’ ‘path3’ ‘path4’ in a script called ‘WaypointScript’. Based on a number I supply it (1-4) it must go through the Array and save each path object from each way object in another array.

For example: Should the number supplied be 3, it would run through each way object and add the path3 variable to a new array. Resulting (If there were 4 way objects) with an array containing way1’s path3, way2’s path 3, way3’s path3 and way4’s path3.

Thanks a lot, I hope to learn from any answers I receive (Im not just being lazy)

Can you post this script?

–

Hang on, think I'm getting my head around it - why are you storing them as path1, path2 though - surely that should be an array as well?

–

There will only ever be 4, so I just created 4 different variables. Personal preference I guess.

–

Much harder to write the code to access them though...

–

well you can make an array: GameObject[] Path = new GameObject[4]; and here you have 4 new Game Object and you access them Path[0] = ... ...; and you can do a for loop if you'll have to there you can't

–

1 Answer

1

I’d suggest you put your path1, path2 etc into an array. Then you can get your new array like this:

  import System.Linq;

  ...

  var taggedObjects = GameObject.FindGameObjectsWithTag("way");
  var pathNumber = 3;
  var path3 = taggedObjects
        .OrderBy(function(g) g.name)
        .Select(function(g) g.GetComponent(WayPointScript).path[pathNumber-1])
        .ToArray();

Using your existing method:

  var taggedObjects = GameObject.FindGameObjectsWithTag("way");
  var pathNumber = 3;
  var path3 = taggedObjects.OrderBy(function(g) g.name).Select(function(g) {
         var wayPointScript = g.GetComponent(WayPointScript);
         if(pathNumber == 1)
              return wayPointScript.path1;
         if(pathNumber == 2)
              return wayPointScript.path2;
         if(pathNumber == 3)
              return wayPointScript.path3;
         if(pathNumber == 4)
              return wayPointScript.path4;
  }).ToArray();

Actually a switch rather than those ifs to be honest.

–

Im getting a missing Method exception for .OrderBy

–

At the top of your source: import System.Linq;

–

still happening :(

–

I don't understand that works fine for me - see attached: W[9374-pathfinding.unitypackage.zip|9374]W

–