Search Unity

Spawning Prefabs with Dynamic PhysicsBodies at given a position

Discussion in 'Physics for ECS' started by Srokaaa, Feb 1, 2020.

  1. Srokaaa

    Srokaaa

    Joined:
    Sep 18, 2018
    Posts:
    169
    I would like to be able to spawn a group of dynamic bodies at some runtime-determined position. It works ok for me as long as I try to spawn a single Prefab with PhysicsBody like this:

    Code (CSharp):
    1.                    
    2. var spawnedEntity = commandBuffer.Instantiate(entityInQueryIndex, myEntityPrefab);
    3. commandBuffer.SetComponent(entityInQueryIndex, spawnedEntity, someArbitraryTranslation);
    4.  
    As soon I try to do this with a nested prefab:

    -PrefabRoot(without PhysicsBody)
    ----MyPhysicsBody1
    ----MyPhysicsBody2
    ----MyPhysicsBody3
    ----MyPhysicsBody4
    ...

    all of my entities with PhysicsBody are not translated by the translation set to their parent but are instead spawned with the translation originally set to PrefabRoot in the editor.

    This makes sense since in the source code of Unity.Physics.Hybrid/Conversion/ConversionExtensions.cs we can find:


    Code (CSharp):
    1.            
    2.             manager.RemoveComponent<Parent>(entity);
    3.             manager.RemoveComponent<LocalToParent>(entity);
    4.             manager.AddOrSetComponent(entity, new Translation { Value = worldTransform.position });
    5.             manager.AddOrSetComponent(entity, new Rotation { Value = worldTransform.rotation });
    6.  
    Problem with this is that it sets the translations of my bodies right when I click Play (so when conversion systems run) rather than when the prefab actually get spawned.

    Does anyone know a way around that?
     
  2. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    The SpawnRandomObjectsAuthoring.cs might be useful for you.
    A number of the UnityPhysicsSamples scene extend it, to modify prefabs, instances and components at different stages.