Reputation: 1728
Im calling Texture2D function on void OnGUI().And Im adding 5 prefabs in 5 seconds and those are destroying in 20 seconds. This all prefabs using Texture2D. I'm not destroying Texture after use. When I run this game, it use lot of memory and it is increasing. Shoud I need to destroy this generated Texture?
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;
}
Edit
Ok. This is what I actualy try to do. I have a class Called 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;
}
}
Im calling this from another script
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);
}
This script attached to my eminy troops. 5 enemies are spowning by 5 second. And they will be destroyed in 20 seconds. This enemy object are using Physics.OverlapSphere to identify their enemies
Upvotes: 0
Views: 167
Reputation: 1076
OnGUI is called one time per frame. so dont instantiate or create any thing in OnGUI. Unlikely what you think, it doesnt create just one texture. Every frame it creates one new texture. Creating and deleting also will be a bad code. you need to create this texture in void Start()
Upvotes: 1