c# - 如何在一个脚本中使用合并列表中的两个对象?

标签 c# unity3d pooling

我正在尝试了解对象池。我能够让脚本一次拉取一个对象,但我需要能够同时从列表中拉取三个或更多对象。

我的对象池脚本很大,所以除非必要,否则我真的不想分享整个东西。

我需要能够改变火焰产生的位置,所以我创建了一个脚本来做到这一点:

 private void CreateWavesForFlames(GameObject flame, float xBase, float xDisplacement, float dropHeight)
 {
    flame.transform.position = new Vector3(xBase + xDisplacement, dropHeight, 0);
    flame.SetActive(true); //this turn the pooled object on
} 

所以我需要同时生成三个火焰并更改它们的生成位置

wave 调用看起来像这样:

void Wave1() {
    Debug.Log("Wave1");
    tempGOHolder = gm.GetLargeFire();


    CreateWavesForFlames(tempGOHolder, 0, 0, 12);
    CreateWavesForFlames(tempGOHolder, 10, 0, 12);
    CreateWavesForFlames(tempGOHolder, 15, 0, 12);

}

只创建了一个火焰,它使用了最后一个 CreatWavesForFlames。我需要三个不同。

关于如何执行此操作的任何建议都很棒。

最佳答案

我知道这个问题已经得到解答,但我认为还有更好的解决方案。上面的答案很棒。假设您希望通过不重复调用 GetLargeFire() 函数来缩短代码,您可以使用以下方法。

假设您的池脚本中的 GetLargeFire() 函数如下所示:

GameObject GetLargeFire()
{
    return availableGameObject;
}

您可以创建 GetLargeFire() 函数的重载,以填充传递给它的数组。我不建议返回数组,因为它会分配内存,从而使您的池脚本无用。填充传入的数组更好。

public void GetLargeFire(GameObject[] gOBJ, int amountToReturn)
{
    for (int i = 0; i < gOBJ.Length; i++)
    {
        if (i < amountToReturn)
        {
            gOBJ[i] = GetLargeFire();
        }
        else
        {
            //Fill the rest with null to override what was inside of it previously
            gOBJ[i] = null;
        }
    }
}

现在,要像问题中的示例一样使用它,您应该将 tempGOHolder 声明为数组并选择您认为足够的数字。我们将在本示例中使用 3

GameObject[] tempGOHolder;

void Start()
{
    tempGOHolder = new GameObject[3];
}

void Wave1() {
    Debug.Log("Wave1");
    gm.GetLargeFire(tempGOHolder, 3);
    CreateWavesForFlames(tempGOHolder[0], 0, 0, 12);
    CreateWavesForFlames(tempGOHolder[1], 10, 0, 12);
    CreateWavesForFlames(tempGOHolder[2], 15, 0, 12);
}

您甚至可以使用循环通过 CreateWavesForFlames 创建 Waves,代码更少。

关于c# - 如何在一个脚本中使用合并列表中的两个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428489/

相关文章:

c# - 在编辑器上突出显示括号

android - 打开带附件的短信应用程序

ajax - 轮询与长轮询

c# - 尝试从 Azure 检索数据时出现 MobileServiceInvalidOperationException

c# - 从 C# Web 应用程序登录 SQL Server 失败

c# - unity 在着色器调用之前在哪里丢弃顶点?

c# - 角色在 Unity 中使用人形动画类型慢慢向上移动

python - Keras 中具有掩蔽支持的均值或最大池化

c++ - 平均池 C++ 错误

c# - wpf默认样式和样式基础