AttachmentScript.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using GPUECSAnimationBaker.Engine.AnimatorSystem;
  2. using Unity.Burst;
  3. using Unity.Collections;
  4. using Unity.Entities;
  5. using Unity.Transforms;
  6. using UnityEngine;
  7. namespace GPUECSAnimationBaker.Samples.SampleScenes._5_Attachments
  8. {
  9. public class AttachmentScript : MonoBehaviour
  10. {
  11. public int attachmentToSetIndex;
  12. public void Attach()
  13. {
  14. AttachmentScriptSystem blendScriptSystem =
  15. World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged<AttachmentScriptSystem>();
  16. blendScriptSystem.changeAttachments = true;
  17. blendScriptSystem.attachmentToSetIndex = attachmentToSetIndex;
  18. }
  19. }
  20. public partial class AttachmentScriptSystem : SystemBase
  21. {
  22. public bool changeAttachments;
  23. public int attachmentToSetIndex;
  24. protected override void OnUpdate()
  25. {
  26. if (changeAttachments)
  27. {
  28. changeAttachments = false;
  29. EntityManager entityManager = World.EntityManager;
  30. Entity gpuEcsAnimatorEntity = SystemAPI.GetSingletonEntity<AttachmentPrefabBufferElement>();
  31. DynamicBuffer<AttachmentPrefabBufferElement> attachments = SystemAPI.GetSingletonBuffer<AttachmentPrefabBufferElement>();
  32. AttachmentPrefabBufferElement attachmentPrefab = attachments[attachmentToSetIndex];
  33. EntityCommandBuffer ecbDelete = new EntityCommandBuffer(Allocator.Temp);
  34. Entities.ForEach((
  35. in GpuEcsAttachmentComponent gpuEcsAttachment,
  36. in Entity entity
  37. ) =>
  38. {
  39. if(gpuEcsAttachment.attachmentAnchorId == (int)attachmentPrefab.anchor)
  40. ecbDelete.DestroyEntity(entity);
  41. }).Run();
  42. ecbDelete.Playback(entityManager);
  43. Entity newAttachment = entityManager.Instantiate(attachmentPrefab.attachmentPrefab);
  44. entityManager.AddComponent<Parent>(newAttachment);
  45. entityManager.SetComponentData(newAttachment, new Parent()
  46. {
  47. Value = gpuEcsAnimatorEntity
  48. });
  49. entityManager.AddComponent<GpuEcsAttachmentComponent>(newAttachment);
  50. entityManager.SetComponentData<GpuEcsAttachmentComponent>(newAttachment, new GpuEcsAttachmentComponent()
  51. {
  52. attachmentAnchorId = (int) attachmentPrefab.anchor,
  53. gpuEcsAnimatorEntity = gpuEcsAnimatorEntity
  54. });
  55. }
  56. }
  57. }
  58. }