Unity3d中的内存管理问题

时间:2015-10-19 04:55:11

标签: memory-management unity3d texture2d

我在void OnGUI()上调用Texture2D函数。并且我在5秒内添加了5个预制件,并且这些预制件在20秒内被破坏。这个所有预制件都使用Texture2D。使用后我没有破坏纹理。当我运行这个游戏时,它会占用大量内存而且还在增加。我需要破坏这个生成的纹理吗?

public static Texture2D Colors(int r,int g, int b)
    {
        Texture2D texture = new Texture2D(2, 2);
        for (int y = 0; y < texture.height; ++y)
        {
            for (int x = 0; x < texture.width; ++x)
            {

                Color color = new Color(r, g, b);
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();

        return texture;
    }

修改

确定。这就是我实际尝试做的事情。我有一个名为HealthSystem的课程 On Github

using UnityEngine;
using System.Collections;

public class HealthSystem : MonoBehaviour {
float healthBarLenght=20f;//Length for Healthbar;

public static void Set_HealthBar(Transform transform,int HealthBarHeight,   float CurrentHealth,float MaxHealth,Texture2D BackBar, Texture2D FrontBar)
        {
        Vector3 screenPosition;

        GUIStyle style1 = new GUIStyle();
        GUIStyle style2 = new GUIStyle();
        float HPDrop = (CurrentHealth / MaxHealth) * healthBarLenght;

        screenPosition = Camera.main.WorldToScreenPoint(transform.position);
        screenPosition.y = Screen.height - screenPosition.y;

        style1.normal.background = BackBar;
        GUI.Box(new Rect(screenPosition.x-(healthBarLenght/2),screenPosition.y-20, healthBarLenght,HealthBarHeight),"",style1);

        style2.normal.background = FrontBar;
        GUI.Box(new Rect(screenPosition.x-(healthBarLenght/2),screenPosition.y-20, HPDrop,HealthBarHeight),"",style2);
}


    public static Texture2D Colors(int r,int g, int b)
    {
        Texture2D texture = new Texture2D(2, 2);
        for (int y = 0; y < texture.height; ++y)
        {
            for (int x = 0; x < texture.width; ++x)
            {               
                Color color = new Color(r, g, b);
                texture.SetPixel(x, y, color);
            }
        }
        texture.Apply();
        return texture;
    }
}

我从另一个脚本中调用它

void Start () {
        colorback = HealthSystem.Colors (0, 0, 0);
        colorfront = HealthSystem.Colors (0, 255, 0);
    }

void OnGUI(){

            HealthSystem.Set_HealthBar (transform, 2f, 70f, 100f, colorback, colorfront);

    }

这个剧本附在我的狡猾部队身上。 5个敌人将在5秒钟内施放。它们将在20秒内被摧毁。这个敌人的对象正在使用Physics.OverlapSphere来识别他们的敌人

1 个答案:

答案 0 :(得分:1)

每帧调用一次OnGUI。所以不要在OnGUI中实例化或创建任何东西。不像你想的那样,它不会只创造一个纹理。每一帧都会创建一个新纹理。创建和删除也将是一个糟糕的代码。你需要在void Start()

中创建这个纹理