![](/img/trans.png)
[英]Taking a screenshot from one of the Camera GameObjects when the game is running and then output
[英]Why is my code generating two gameObjects(instead of one) at a time when one gameObject out of the Camera view is destroyed?
我自己編寫了用於飛鳥類游戲的腳本(學習統一腳本的最佳方法)。 為了優化性能,我想一次只生成5個Obstacle gameObjects(ObjectsOnScreen)。所以我編寫了一個代碼來在離玩家16個單位的情況下銷毀gameObject,並且編寫了一個少於5個ObjectsOnScreen的新障礙物。 。 但是我的代碼破壞了一個障礙物,同時生成了兩個對象(而不是一個),因此最終對象將隨着時間的推移而增加,並保持不變。 請告訴我我的代碼中的錯誤。
//GameManager script::
public class GameManager : MonoBehaviour
{
static public int ObjectsOnScreen = 0;
public float poleDistance;
public int gapWidth;
static public bool reset=false;
float x = 8;
int gap;
public GameObject obstacle;
void FixedUpdate()
{
if(reset)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
if(ObjectsOnScreen<5)
{
gap = Random.Range(-6, 6);
GenerateObstacle(x, gap);
x += poleDistance;
Debug.Log("gap = " + gap);
ObjectsOnScreen++;
}
}
void GenerateObstacle(float x , float gap)
{
GameObject Top = Instantiate(obstacle, new Vector3(x, 8, 0) , Quaternion.identity);
GameObject Bottom = Instantiate(obstacle, new Vector3(x, -8, 0), Quaternion.identity);
Top.transform.localScale = new Vector3(1, (8 - gap)-gapWidth, 1);
Bottom.transform.localScale = new Vector3(1, -(8 + gap)+gapWidth, 1);
}
}
//Obstacle Script::
public class ObstacleScript : MonoBehaviour
{
GameObject player;
void Awake()
{
player = GameObject.Find("Player");
}
void FixedUpdate()
{
if ((transform.position.x - player.transform.position.x) <= -16)
{
GameManager.ObjectsOnScreen--;
Destroy(gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
PlayerScript player = collision.gameObject.GetComponent<PlayerScript>();
if(player!=null)
{
GameManager.reset = true;
}
}
}
您在GenerateObstacle
函數中調用了兩次實例化,這將實例化兩個對象(而不是一個)。
GameObject Top = Instantiate(obstacle, new Vector3(x, 8, 0) , Quaternion.identity);
GameObject Bottom = Instantiate(obstacle, new Vector3(x, -8, 0), Quaternion.identity);
但是,然后您正在執行ObjectsOnScreen++
,它僅增加一。 然后,兩個障礙物將自己刪除,從而有效地減少了兩次。
您可能應該增加兩個ObjectsOnScreen += 2
以獲得准確的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.