2017-04-24 58 views
1

此代碼來自我正在製作的遊戲。目的是收集火箭零件。當零件被收集後,它們意味着隨後消失,但是當你嘗試收集第二個零件時,它不會將它添加到零件變量中。我的代碼存在一些問題

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

public class Collection : MonoBehaviour { 

private int Parts; 
public Text CountPart; 
private string Amount; 

void Start() 
{ 
    Parts = 0; 
    SetPartText(); 
} 

// Update is called once per frame 
void Update() { 
    if (Parts == 10) 
    { 
     Application.LoadLevel("DONE"); 
    } 
} 

void OnMouseDown() 
{ 
    gameObject.SetActive(false); 
    Parts = Parts + 1; 
    SetPartText(); 
} 

void SetPartText() 
{ 
    Amount = Parts.ToString() + "/10"; 
    CountPart.text = "Rocket Parts Collected: " + Amount; 
} 
} 
+0

'「它不將它添加到變量部分」' - 你什麼意思那?這裏真的失敗了嗎? – David

+0

一旦玩家收集到包含該腳本的10個火箭零件中的第一個零件變量,然後禁用該火箭零件,但是當用戶繼續收集第二個火箭零件時,它禁用第二個火箭零件,但是它不會在零件變量中加上一個 – Joshua

+0

確實如此,在這裏:'Parts = Parts + 1;'這聽起來像是一個開始使用調試器的好機會。您可以逐行執行代碼,執行代碼並觀察運行時值和行爲。當你這樣做時,觀察到的行爲具體與預期行爲有什麼不同?具體發生了什麼,你期望發生什麼? – David

回答

0

首先,你需要考慮用例在這裏你要收集的火箭部件,然後隱藏/摧毀它們並在你的遊戲對象添加一個部件數量。

但是,您當前的代碼存在一個問題,您可以停用當前收集零件的玩家,因此當您收集停用玩家的第一部分時,您將無法收集其他物品。

的解決辦法是讓你收集部分的引用,然後使其SETACTIVE(假)

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

public class Collection : MonoBehaviour { 

private int Parts; 
public Text CountPart; 
private string Amount; 
public GameObject collectedGameObject; 
void Start() 
{ 
    Parts = 0; 
    SetPartText(); 
} 

// Update is called once per frame 
void Update() { 
    if (Parts == 10) 
    { 
     Application.LoadLevel("DONE"); 
    } 
} 

void OnMouseDown() 
{ 
     //here you need to initialize the collectedGameObject who is collected. you can use Raycasts or Colliders to get the refrences. 
    collectedGameObject.SetActive(false); 
    Parts = Parts + 1; 
    SetPartText(); 
} 

void SetPartText() 
{ 
    Amount = Parts.ToString() + "/10"; 
    CountPart.text = "Rocket Parts Collected: " + Amount; 

} 
}