2017-04-25 12 views
0

私は現在Unity内のアンドロイド向けのアプリを開発中です。 C#のスクリプト。ゲームは垂直スクロールであり、無限にゲームオブジェクト(私の場合はサークル)のプールが欲しいです。私が抱えている問題は、オブジェクトプールが生成されず、それをリバーしたり再生成したりすることができないときです... 私は数時間前にそれに行ってきました。どこにも行きません。ここに私のコードがあります。Unityのスクリーンショットもリンクします。C#Unity 2D Object Pooling

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; 
    } 
    } 
} 
} 

enter image description here FYI:ゲーム内の小さな円は常に鉛直上方に移動され、大きな円は障害物のいくつかの並べ替えに変換されますが、今のところ、私はちょうどそれがうまく復活させたい:)。

+3

本当に機能しないのですか?スクリーンショットでは、8つのオブジェクトが作成されています。私が見ることができるコードの問題は、あなたが "spawnYPosition"変数を使用していないことだけです。 – CaTs

答えて

0

投稿のCaTコメントに追加するには、ロジックが正しいように見えますが、変換の位置を設定する行は例外です。あなたはspawnXPositionとspawnYPositionのどちらも使用していません。

はこれを変更してみてください:

circles[currentCircle].transform.position = new Vector2(0, +2); 

これに:GameController.instance.gameOverに設定された場合、それは火にあなたのスポーンタイマーを妨げるように思える

circles[currentCircle].transform.position = new Vector2(spawnXPosition, spawnYPosition); 

唯一の他の事はあります本当。いくつかのデバッグステートメントを追加したり、デバッガを使ってこれを確認したりすることがあります。

Debug.Log("Is the game over? " GameController.instance.gameOver); 
関連する問題