C#Unity 2D对象池
问题描述:
我目前正在为Unity内的android应用程序工作。在C#中编写脚本。游戏是一个垂直滚动条,我想要一个无限生成的游戏对象池(在我的情况下是圈子)。我遇到的问题是对象池不会产生,当我可以让它产生在它不回收和重生... 我已经在它几个小时了,我是没有到任何地方。这里是我的代码,我也会链接Unity的屏幕截图。C#Unity 2D对象池
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CirclePool : MonoBehaviour {
public GameObject BigCircle; //the circle game object
public int circlePoolSize = 8; //how many circles to keep on standby
public float spawnRate = 1f; //how quickly circles spawn
public float circleMin = 3; //minimum y value of circle pos
public float circleMax = 7; //max value
private GameObject[] circles; //collection of pooled circles
private int currentCircle = 0; //index of the current circle in the collection
private Vector2 objectPoolPosition = new Vector2(-15, -25); //holding position for unused circles offscreen
private float spawnXposition = 10f;
private float timeSinceLastSpawned;
void Start() {
timeSinceLastSpawned = 0f;
//initialize the circles collection
circles = new GameObject[circlePoolSize];
//loop through collection..
for(int i = 0; i < circlePoolSize; i++)
{
//and create individual circles
circles[i] = (GameObject)Instantiate(BigCircle, objectPoolPosition, Quaternion.identity);
}
}
void Update() {
timeSinceLastSpawned += Time.deltaTime;
if (GameController.instance.gameOver == false && timeSinceLastSpawned >= spawnRate)
{
timeSinceLastSpawned = 0f;
//set random y pos for circle
float spawnYPosition = Random.Range(circleMin, circleMax);
//then set the current circle to that pos
circles[currentCircle].transform.position = new Vector2(0, +2);
//increase the value of currentCircle. if the new size is too big, back to 0
currentCircle++;
if (currentCircle >= circlePoolSize)
{
currentCircle = 0;
}
}
}
}
答
要添加到CaT对您的文章的评论,您的逻辑看起来是正确的,除了设置转换位置的行外。你没有使用spawnXPosition或spawnYPosition。
尝试修改此:
circles[currentCircle].transform.position = new Vector2(0, +2);
要这样:
circles[currentCircle].transform.position = new Vector2(spawnXPosition, spawnYPosition);
这似乎是它会阻止你的重生计时器火灾的唯一其他的事情是,如果GameController.instance.gameOver设置为真正。您可以尝试添加一些调试语句或使用调试器来检查这一点。
Debug.Log("Is the game over? " GameController.instance.gameOver);
你确定它不工作?在你的截图中,我看到8个对象已经创建。只有代码的问题我可以看到你没有使用“spawnYPosition”变量。 – CaTs