Search Unity

RaycastCommand returns 1st hit only regardless of the value assigned to the `maxHit` parameter!

Discussion in 'Data Oriented Technology Stack' started by Backer_Sultan, Sep 9, 2019.

  1. Backer_Sultan

    Backer_Sultan

    Joined:
    Nov 5, 2018
    Posts:
    5
    RaycastCommand has a parameter called `maxHits` and descriped as: The maximum number of Colliders the ray can hit. (https://docs.unity3d.com/ScriptReference/RaycastCommand.html)

    The thing is that it never hits more than one object regardless of the number you pass to the `maxHits` parameter.

    According to the description: The result for a command at index N in the command buffer will be stored at index N * maxHits in the results buffer.

    According to this description, if I write the following code:
    ```
    var results = new NativeArray<RaycastHit>(6, Allocator.Temp);

    var commands = new NativeArray<RaycastCommand>(2, Allocator.Temp);

    // Set the data of the first command
    Vector3 origin = Vector3.forward * -10;
    Vector3 direction = Vector3.forward;

    commands[0] = new RaycastCommand(origin, direction, maxHits: 3);
    commands[1] = new RaycastCommand(origin, direction, maxHits: 2);
    ```
    After the job is complete, the results array should look like this:
    results[0] is first hit from first command
    results[1] is second hit from first command
    results[2] is third hit from first command
    results[4] is first hit form second command
    results[5] is second hit from second command.


    The actual output is quite different. It's actually:
    results[0] is first hit from first command
    results[1] is second hit from first command
    results[2..5] memory garbage as `results[2].collider = null` is true.

    Am I missing something here or is it really not working as it's supposed to?
     
  2. eizenhorn

    eizenhorn

    Joined:
    Oct 17, 2016
    Posts:
    1,423
  3. Backer_Sultan

    Backer_Sultan

    Joined:
    Nov 5, 2018
    Posts:
    5
    @eizenhorn so the documentation is not correct. They should probably reflect what the command does more clearly.
     
  4. Abbrew

    Abbrew

    Joined:
    Jan 1, 2018
    Posts:
    144
    You could implement your own version of raycast with multiple hits. Do a normal raycast, and when it hits something, set the start to where it hit plus a small dx in the direction of the original raycast. Keep doing this until you either reach the end of the original raycast or the final raycast does not hit anything. This is far less efficient than a theoretical max hits raycast, but it will work in the meantime

    Edit: consider using Unity.Physics' version of raycast. It can be used inside of a job instead of being a separate atomic job itself like RaycastCommand, allowing for more complex workloads
     
    wobes likes this.