Код: Выделить всё
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class testMemory : MonoBehaviour {
public bool useNewList = false;
Texture2D newTexture;
public byte color;
List newColors;
List staticPixelColorsList;
Color tempColor = Color.white;
// Use this for initialization
void Start () {
newTexture = new Texture2D(0,0);
newColors = new List();
staticPixelColorsList = new List(120000);
GetComponent().material.mainTexture = newTexture;
}
// Update is called once per frame
void Update () {
// Make sure we're using different colors for every frame
color = (byte)((Time.time*255) % 255);
if(useNewList)
{
// This option causes a memory leak, but it's the one I need
// because I'm getting the texture data from an external source
int newWidth = Random.Range(200,400);
int newHeight = Random.Range(200,400);
// Create a new list each time
List newPixels = new List(newWidth * newHeight);
for(int i = 0; i < newWidth * newHeight; i++)
{
newPixels.Add ((byte)(color * i / 120000f));
}
setTexture(newPixels, newWidth, newHeight);
// Clear the list (yeah, right)
newPixels.Clear ();
}
else
{
// Use the same list, but assign new colors
for(int i = 0; i < 120000; i++)
{
staticPixelColorsList.Add ((byte)(color * i / 120000f));
}
setTexture(staticPixelColorsList, 300, 400);
staticPixelColorsList.Clear ();
}
}
void setTexture(List inputPixels, int inputWidth, int inputHeight)
{
newTexture.Resize(inputWidth, inputHeight);
float colorValue;
// Convert input value to Unity's "Color"
for(int n = 0; n < newTexture.width * newTexture.height ; n++)
{
colorValue = inputPixels[n] / 255.0f;
tempColor.r = tempColor.g = tempColor.b = colorValue;
newColors.Add (tempColor);
}
// Actually set the texture pixels
newTexture.SetPixels(newColors.ToArray());
newTexture.Apply();
newColors.Clear();
}
}
Подробнее здесь: https://stackoverflow.com/questions/307 ... emory-leak