2017-04-24 61 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; 

} 
}