ObjectPlacer.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace Pathfinding.Examples {
  4. /// <summary>Small sample script for placing obstacles</summary>
  5. [HelpURL("http://arongranberg.com/astar/documentation/stable/class_pathfinding_1_1_examples_1_1_object_placer.php")]
  6. public class ObjectPlacer : MonoBehaviour {
  7. /// <summary>
  8. /// GameObject to place.
  9. /// When using a Grid Graph you need to make sure the object's layer is included in the collision mask in the GridGraph settings.
  10. /// </summary>
  11. public GameObject go;
  12. /// <summary>Flush Graph Updates directly after placing. Slower, but updates are applied immidiately</summary>
  13. public bool direct = false;
  14. /// <summary>Issue a graph update object after placement</summary>
  15. public bool issueGUOs = true;
  16. /// <summary>Update is called once per frame</summary>
  17. void Update () {
  18. if (Input.GetKeyDown("p")) {
  19. PlaceObject();
  20. }
  21. if (Input.GetKeyDown("r")) {
  22. StartCoroutine(RemoveObject());
  23. }
  24. }
  25. public void PlaceObject () {
  26. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  27. RaycastHit hit;
  28. // Figure out where the ground is
  29. if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
  30. Vector3 p = hit.point;
  31. GameObject obj = GameObject.Instantiate(go, p, Quaternion.identity) as GameObject;
  32. if (issueGUOs) {
  33. Bounds b = obj.GetComponent<Collider>().bounds;
  34. GraphUpdateObject guo = new GraphUpdateObject(b);
  35. AstarPath.active.UpdateGraphs(guo);
  36. if (direct) {
  37. AstarPath.active.FlushGraphUpdates();
  38. }
  39. }
  40. }
  41. }
  42. public IEnumerator RemoveObject () {
  43. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  44. RaycastHit hit;
  45. // Check what object is under the mouse cursor
  46. if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
  47. // Ignore ground and triggers
  48. if (hit.collider.isTrigger || hit.transform.gameObject.name == "Ground") yield break;
  49. Bounds b = hit.collider.bounds;
  50. Destroy(hit.collider);
  51. Destroy(hit.collider.gameObject);
  52. if (issueGUOs) {
  53. // In Unity, object destruction is actually delayed until the end of the Update loop.
  54. // This means that we need to wait until the end of the frame (or until the next frame) before
  55. // we update the graph. Otherwise the graph would still think that the objects are there.
  56. yield return new WaitForEndOfFrame();
  57. GraphUpdateObject guo = new GraphUpdateObject(b);
  58. AstarPath.active.UpdateGraphs(guo);
  59. if (direct) {
  60. AstarPath.active.FlushGraphUpdates();
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }