Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to use EntityManager. AddComponent to add a PhysicsBody component to an Entity?

Discussion in 'Entity Component System' started by LittleWhite114, Jul 30, 2023.

  1. LittleWhite114

    LittleWhite114

    Joined:
    Apr 29, 2019
    Posts:
    9
    How to use EntityManager. AddComponent to add a PhysicsBody component to an Entity? I want to dynamically add this thing, and I don't want to use prefabricated components. I tried this method, but reported an error. The error message is as follows:
    ArgumentException: System.ArgumentException: A component with type:{0} has not been added to the entity.
     
  2. Steffen-ttc

    Steffen-ttc

    Joined:
    May 27, 2017
    Posts:
    20
    Hi LittleWhite114,

    the documentation of the physics package has a part "Creating bodies from scratch" with a full example of exactly your use case. In addition the samples on git are very helpful.
    I used it to modify the PhysicsBody at runtime (I've used SetComponentData, because my object already has a PhysicsBody and PhysicsShape):
    Code (CSharp):
    1. float3 newSize = new float3(Length, Height , Width);
    2.                     BoxGeometry boxGeometry = new BoxGeometry
    3.                     {
    4.                         Size = newSize,
    5.                         Center = new float3(newSize.x / 2, -newSize.y / 2, newSize.z / 2),
    6.                         Orientation = quaternion.identity,
    7.                         BevelRadius = 0.02f
    8.                     };
    9.                     BlobAssetReference<Collider> boxCollider = BoxCollider.Create(boxGeometry);
    10.                     state.EntityManager.SetComponentData(newEntity, new PhysicsCollider
    11.                     {
    12.                         Value = boxCollider
    13.                     });
     
    LittleWhite114 likes this.
  3. LittleWhite114

    LittleWhite114

    Joined:
    Apr 29, 2019
    Posts:
    9
    thank you very much!
     
  4. LittleWhite114

    LittleWhite114

    Joined:
    Apr 29, 2019
    Posts:
    9
    I have encountered another problem. My ultimate goal is to use ray detection technology to select objects with the mouse, but after adding collision objects, it is not possible. It seems that a rigid body needs to be added, but how can this rigid body be added? Thank you for your answer