0
我目前正在爲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;
}
}
}
}
FYI:在遊戲中的小圓圈是不斷向上垂直移動和更大的圓圈會變成某種障礙,但現在我只想把它很好地重生:)。
你確定它不工作?在你的截圖中,我看到8個對象已經創建。只有代碼的問題我可以看到你沒有使用「spawnYPosition」變量。 – CaTs