Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
2.2 kB
3
Indexable
Never
using UnityEngine;
using System.Collections.Generic;

public class CubeRendererInstanced : MonoBehaviour
{
    private Mesh mesh;
    private Material material;
    private List<Matrix4x4> matrices;

    void Start()
    {
        // Create a new Mesh object
        mesh = new Mesh();
        
        // Define the vertices of the cube
        Vector3[] vertices = new Vector3[]
        {
            // Front face
            new Vector3(-1, -1,  1), // Bottom-left
            new Vector3( 1, -1,  1), // Bottom-right
            new Vector3( 1,  1,  1), // Top-right
            new Vector3(-1,  1,  1), // Top-left
            // Back face
            new Vector3(-1, -1, -1), // Bottom-left
            new Vector3( 1, -1, -1), // Bottom-right
            new Vector3( 1,  1, -1), // Top-right
            new Vector3(-1,  1, -1)  // Top-left
        };
        
        // Define the triangles (each face is made up of two triangles)
        int[] triangles = new int[]
        {
            // Front face
            0, 2, 1,
            0, 3, 2,
            // Top face
            2, 3, 6,
            6, 3, 7,
            // Back face
            5, 6, 4,
            6, 7, 4,
            // Bottom face
            0, 1, 4,
            4, 1, 5,
            // Left face
            0, 7, 3,
            0, 4, 7,
            // Right face
            1, 2, 5,
            2, 6, 5
        };

        // Assign vertices and triangles to the mesh
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();

        // Create a simple material
        material = new Material(Shader.Find("Standard"));
        
        // Enable instancing on the material
        material.enableInstancing = true;

        // Optionally, set the material color
        material.color = Color.green;

        // Initialize the matrices list
        matrices = new List<Matrix4x4>();

        // Add a single matrix for the cube at world position (0, 0, 0)
        matrices.Add(Matrix4x4.TRS(Vector3.zero, Quaternion.identity, Vector3.one));
    }

    void Update()
    {
        // Draw the mesh using GPU instancing
        Graphics.DrawMeshInstanced(mesh, 0, material, matrices);
    }
}
Leave a Comment