텍스쳐 캐싱기법



Test.cs 소스입니다

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[Serializable]
public class Item
{
    public int code;
    public Texture2D texture;
}

public class Test : MonoBehaviour
{
    [SerializeField] Item[] items;
    [SerializeField] GameObject block;
    [SerializeField] Material blockMaterial;
    [SerializeField] int code;
    Dictionary<int, Material> materialCodeTable = new Dictionary<int, Material>();


    void Update()
    {
        Vector3 rayDirection = Camera.main.ScreenPointToRay(Input.mousePosition).direction;
        if (Physics.Raycast(Camera.main.transform.position, rayDirection, out RaycastHit raycastHit) && Input.GetMouseButtonDown(0))
        {
            Vector3 point = raycastHit.point + raycastHit.normal * 0.5f;
            GameObject blockObj = Instantiate(block, Vector3Int.RoundToInt(point), Quaternion.identity);
            blockObj.GetComponent<Renderer>().material = GetMaterial();
        }
    }

    public Material GetMaterial()
    {
        if (materialCodeTable.ContainsKey(code))
            return materialCodeTable[code];
        else
        {
            Material material = new Material(blockMaterial);
            material.mainTexture = Array.Find(items, x => x.code == code).texture;
            materialCodeTable.Add(code, material);
            return material;
        }
    }
}