1. 创建C++类继承自AStaticMeshActor
2. 定义用于渲染队列的数据结构
struct FUpdateTextureData
{FTexture2DResource* Texture2DResource;FUpdateTextureRegion2D* UpdateTextureRegion;uint8* DynamicColors;int32 w;
};
3. 增加成员变量
UMaterialInstanceDynamic* mDynamicMaterials;UTexture2D *mDynamicTexture; FUpdateTextureRegion2D* mUpdateTextureRegion;uint8* mDynamicColors; //BGRAconst int32 w = 650;const int32 h = 650;FUpdateTextureData mTextureData;
4. 在PostInitializeComponents函数中初始化材质,颜色内存
mDynamicMaterials = GetStaticMeshComponent()->CreateAndSetMaterialInstanceDynamic(0);if (mDynamicMaterials == nullptr)return;mUpdateTextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, w, h);mDynamicTexture = UTexture2D::CreateTransient(w, h);if (mDynamicTexture == nullptr)return;mDynamicTexture->CompressionSettings = TextureCompressionSettings::TC_VectorDisplacementmap;mDynamicTexture->SRGB = 0;mDynamicTexture->Filter = TextureFilter::TF_Nearest;mDynamicTexture->AddToRoot();mDynamicTexture->UpdateResource();mDynamicMaterials->SetTextureParameterValue("DynamicTextureParam", mDynamicTexture);mDynamicColors = (uint8*)CreatePixelMemory(w, h);mTextureData.Texture2DResource = (FTexture2DResource*)mDynamicTexture->Resource;mTextureData.UpdateTextureRegion = mUpdateTextureRegion;mTextureData.DynamicColors = mDynamicColors;mTextureData.w = w;
5. 创建更新函数
void AMyStaticMeshActor::UpdateTexture()
{if (mDynamicMaterials == nullptr || mDynamicTexture == nullptr || mDynamicTexture->Resource == nullptr || mUpdateTextureRegion == nullptr || mDynamicColors == nullptr)return;ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(UpdateTexture,FUpdateTextureData, TextureData, mTextureData,{RHIUpdateTexture2D(TextureData.Texture2DResource->GetTexture2DRHI(),0,*TextureData.UpdateTextureRegion,TextureData.w * 4,TextureData.DynamicColors);});mDynamicMaterials->SetTextureParameterValue("DynamicTextureParam", mDynamicTexture);
}
6. 在tick函数中调用更新函数
7. 在endplay函数中释放内存
if (mUpdateTextureRegion){delete mUpdateTextureRegion;mUpdateTextureRegion = nullptr;}
8. 直接将此类拖入的场景中,并且设置其static mesh,材质,并且设置材质的空白纹理