2017-07-25 54 views
0

我目前工作的一個遊戲原型,這個遊戲將需要 產卵一些GameObjects我稱之爲「明星」,都好有 實例化,但是當我試圖刪除它們時,有許多 周圍不工作,我試圖將所有實例化的GameObjects放入一個列表中,然後在 實例化後刪除最後一個對象。從代碼中可以看到,當產生3 對象時,腳本應該從開頭 中刪除一個,並在同一時間產生一個新對象。爲什麼GameObject不會附加到列表中?

現在,問題是我不知道我在這裏錯過了什麼,代碼不起作用,我不知道爲什麼。請幫幫我。謝謝!

下面是代碼:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class SpawnStar : MonoBehaviour { 

    public float addedSpeed = -200f; 

    private GameObject spawned; 
    private float randomX; 
    public GameObject starToSpawn; 
    private List<GameObject> activeGO; 


    void Start() 
    { 
     activeGO = new List<GameObject>(); 
     Invoke ("InstantiateStar", 2f); 
    } 

    // Update is called once per frame 
    void FixedUpdate() 
    { 
     GetComponent<Rigidbody>().AddForce(new Vector3(0f, addedSpeed, 0f)); 
    } 

    void InstantiateStar() 
    { 
     randomX = Random.Range (-3f, 3f); 
     GameObject GO; 
     GO = Instantiate (starToSpawn, new Vector3(randomX, 5f, 0f), transform.rotation) as GameObject; 
     activeGO.Add (GO); 
     if (activeGO[0].transform.position.y < -2f) 
     { 
      DeleteActiveGO(); 
     } 
    } 
    void DeleteActiveGO() 
    { 
     Destroy (activeGO [0]); 
     activeGO.RemoveAt (0); 
    } 
} 

我回來了更新。問題是我試圖在一個腳本中做兩件事......短篇小說:爲了解決這個問題,我在場景中創建了一個空對象,將我的腳本分成兩個分離的腳本,一個讓生成的對象更快地移動,一個是產生對象的東西,我把把對象移動到將要產生的對象的腳本上,另一個腳本放在空的GameObject上,它會產生「星星」,它就像一個魅力一樣工作。 謝謝你的答案!

這裏是最終腳本:

產卵腳本:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class SpawnStars : MonoBehaviour { 

    public GameObject[] starsToSpawn; 

    private List<GameObject> spawnedStars; 

    private float randomX; 

    void Start() 
    { 
     spawnedStars = new List<GameObject>(); 
     InvokeRepeating ("SpawnStar", 0f, 3f); 
    } 
    void SpawnStar() 
    { 
     randomX = Random.Range (-3, 3); 
     GameObject GO; 
     GO = Instantiate (starsToSpawn[0], new Vector3 (randomX, 5f, 0f), transform.rotation); 

     spawnedStars.Add (GO); 

     if (spawnedStars.Count > 2) 
     { 
      Destroy (spawnedStars [0]); 
      spawnedStars.RemoveAt (0); 
     } 
    } 
} 

移動腳本:

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 

public class MoveStar : MonoBehaviour { 

    public float acceleration = -5f; 

    void FixedUpdate() 
    { 
     GetComponent<Rigidbody>().AddForce(new Vector3(0f, acceleration,0f)); 
    } 
} 
+3

請問你能更具體嗎? 「守則不起作用」相當模糊。 – travisjayday

+1

在代碼中,你會檢查是否有三個對象被產生?我看到的唯一代碼會在y座標超出範圍時刪除星號。另外,「starToSpawn」設置爲什麼?因爲看起來你的'FixedUpdate'正在移動'SpawnStar'遊戲對象,而不是產生的星星,這意味着你的任何明星都不會刪除。你的星星真的在移動嗎? –

+0

Yhea,我犯了一些錯誤,腳本被附加到我想要刪除的對象上... – Noobie

回答

0

你的代碼Invoke ("InstantiateStar", 2f);只能叫一次。

你可以改變InvokeRepeating("InstantiateStar",2f,2f);

守則GetComponent<Rigidbody>().AddForce(new Vector3(0f, addedSpeed, 0f));看起來應重視生成遊戲對象。

另請注意您的刪除條件。

祝你好運。

相關問題