Search code examples
c#raytracing

I'm following a Unity path tracing tutorial and I'm getting this error about using .Select on an Int type but I have no idea what the line does


Perhaps following a Unity shader tutorial without any experience in C# wasn't the best idea. :P

Here's the full error:

'int[]' does not contain a definition for 'Select' and no accessible extension method 'Select' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)

Below is the full method that the line is in. If anyone could please help me, I would much appreciate it.

private void RebuildMeshObjectBuffers()
    {
        if(!_meshObjectsNeedRebuilding)
            return;
        
        _meshObjectsNeedRebuilding = false;
        _currentSample = 0;
        
        //Clear lists
        _meshObjects.Clear();
        _vertices.Clear();
        _indices.Clear();
        
        // Loop over all objects and gather their data
        foreach (RayTracingObject obj in _rayTracingObjects)
        {
            Mesh mesh = obj.GetComponent<MeshFilter>().sharedMesh;
            // Add vertex data
            int firstVertex = _vertices.Count;
            _vertices.AddRange(mesh.vertices);
            // Add index data - if the vertex buffer wasn't empty before, the
            // indices need to be offset
            int firstIndex = _indices.Count;
            var indices = mesh.GetIndices(0);
            _indices.AddRange(indices.Select(index => index + firstVertex));
            // Add the object itself
            _meshObjects.Add(new MeshObject()
            {
                localToWorldMatrix = obj.transform.localToWorldMatrix,
                indices_offset = firstIndex,
                indices_count = indices.Length
            });
        }
        
        CreateComputeBuffer(ref _meshObjectBuffer, _meshObjects, 72);
        CreateComputeBuffer(ref _vertexBuffer, _vertices, 12);
        CreateComputeBuffer(ref _indexBuffer, _indices, 4);
    }

Solution

  • You want to use .Select which is a linq function.

    Mesh.GetIndices() returns an array of int for which the .Select() function is not available.

    What you can do is convert to a list first:

                var indices = mesh.GetIndices(0);
                _indices.AddRange(indices.ToList().Select(index => index + firstVertex));
    

    Also see: https://learn.microsoft.com/en-us/dotnet/api/system.linq?view=net-5.0

    Edit:

    Some additional info, it seems you don't need ToList, you were simply missing the import (using System.Linq). As far as i can see .Select() should be available on int[] depending on your framework version; e.g. https://dotnetfiddle.net/oBPIbM