繁体   English   中英

在Unity中每隔一定数量的帧创建和销毁游戏对象

[英]Creating and destroying game objects each certain number of frames in Unity

我正在尝试创建对象并将其每50帧删除一次。 线对象已成功创建,但从未销毁! 我什至尝试了destroyimmediate()仍然无法正常工作..请帮助...我的代码从未像这样工作过::

private int _currentInterval = 50;
private int _maxIntervalValue = 50; 
private int i = 0;

// Update is called once per frame
void Update () {
    if (_currentInterval == _maxIntervalValue)
    {
        float x = Random.Range(-10.0f, 10.0f), y = Random.Range(-10.0f, 10.0f);
        DrawRay(i, new Vector3(0, 0, 0), new Vector3(x, 10, y));
        i++;
        _currentInterval--;
    }
    else if (_currentInterval <= 0)
    {
        Destroy(GameObject.Find("Ray_" + i));
        _currentInterval = _maxIntervalValue;
    }
    else
        _currentInterval--;
}

private void DrawRay(int ID, Vector3 StartPoint, Vector3 EndPoint)
{
    #region Create Line
    GameObject Ray = new GameObject();
    Ray.transform.position = StartPoint;
    Ray.AddComponent<LineRenderer>();
    Ray.name = "Ray_" + ID;
    LineRenderer lr = Ray.GetComponent<LineRenderer>();
    lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply"));
    lr.SetColors(Color.red, Color.red);
    lr.SetWidth(0.05f, 0.05f);
    lr.SetPosition(0, StartPoint);
    lr.SetPosition(1, EndPoint);
    #endregion
}

只需使您的计数器Destroy(GameObject.Find("Ray_" + (i-1))); 现在,它正在尝试查找的GameObject.Find超出了您当时尚未存在的原始值一个计数。 这样可以解决您的对象不被破坏的问题。

在开始时,计数器将为= 50,它将创建一个对象,然后将其一直减小到= 0,这时应该删除我们刚刚创建的对象

1。当实例化类似GameObject Ray = new GameObject();的对象时, GameObject Ray = new GameObject(); 您需要使GameObject Ray变量成为全局变量,以便您可以访问它并在以后销毁它。 这比用GameObject.Find查找来销毁它要好。

2。您不需要代码中的大多数变量。 通过检查Time.frameCount % 50是否为0可以使用Time.frameCount简化操作。

3。不要命名您的变量Ray因为有一个Unity API可以命名。

您尝试执行的代码的简化版本。 DrawRay被删除,但是您可以添加它。

GameObject obj = null;

void Start()
{
    //Create new one
    obj = new GameObject();
}

void Update()
{
    //Check if 50 frames has passed
    if (Time.frameCount % 50 == 0)
    {
        //Destroy old one
        if (obj != null)
            DestroyImmediate(obj);

        //Create new one again
        obj = new GameObject();
    }
}

不要DrawRay函数中使用该代码。 每次创建新Material时,代码中都会发生内存泄漏。 使用对象池重新使用对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM