我的代码有些问题

时间:2017-04-24 12:48:11

标签: c# user-interface variables unity3d

此代码来自我正在制作的游戏。目的是收集火箭部件。收集零件时,它们会在之后消失,但是当您尝试收集第二个零件时,它会将其添加到零件变量中。

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

1 个答案:

答案 0 :(得分:0)

首先,您需要考虑这里的用例,您想要收集火箭部件,然后隐藏/销毁它们,并在游戏对象中添加部件数。

但您当前的代码存在一个问题,即您停用当前收集零件的玩家,因此当您收集第一部分时,您将停用该播放器,以便您无法收集其他项目。

解决方案是获取您收集的部分的引用,然后将其设置为setActive(false)

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;

}
}