Unity性能优化 对象延迟创建

///by邓陶然
using UnityEngine;


public class LaterCreator : MonoBehaviour
{
public delegate GameObject CreatorCallBack();
public CreatorCallBack _creatorCallBack;
public System.Object CallBackObj;


    /// 
    /// 获取已创建成功的对象。
    /// 
    public GameObject CreatedGameObject { get; private set; }
    
private bool allreadyCreator;
    private UIWidget uiw;
public UIPanel panel;
    public bool alwaysShow;

    private void Start ()
{
if(panel == null)
{
panel = GetComponentInParent();
}
}
    /// 
    /// 设置单元大小
    /// 
    /// 
public void SetSize(Vector3 size)
{
uiw = gameObject.AddComponent();
uiw.SetRect(0,0,size.x,size.y);
// Update();
}


private void OnEnable()
{
if(panel == null)
{
panel = GetComponentInParent();
}
}


private void Update ()
{
if(IsInView())
{
if(allreadyCreator && CreatedGameObject != null)
{
CreatedGameObject.SetActive(true);
}
else
{
if(_creatorCallBack != null && !allreadyCreator)
{
                    CreatedGameObject = _creatorCallBack();
                    allreadyCreator = true; 
}
}
}
else
{
if(allreadyCreator && CreatedGameObject != null)
{
                if (alwaysShow)
   {
                    CreatedGameObject.SetActive(true);
   }
   else
   {
                    CreatedGameObject.SetActive(false);
   }

}
}
}

    public void Reflush()
{
Update();
}


    /// 
    /// 强制创建或使对象可见
    /// 
public void ForceOpen()
{
if(allreadyCreator && CreatedGameObject != null)
{
CreatedGameObject.SetActive(true);
}
else
{
if(_creatorCallBack != null && !allreadyCreator)
{
CreatedGameObject = _creatorCallBack();
allreadyCreator = true;
}
}
}
    /// 
    /// 是否在视图中可见
    /// 
    /// 
    private bool IsInView()
    {
        if (panel == null)
        {
            return false;
        }
        return panel.IsVisible(uiw);
    }
}

 
 

你可能感兴趣的:(Unity)