简体   繁体   中英

I have some issues with my code

This code is from a game I am making. The aim is to collect rocket parts. As the parts are collected they are meant to disappear afterwards, but once you pick up one when you try and collect a second one it doesn't add it to the parts variable.

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

First, you need to think about the use case here you want to collect the rocket parts and then hide/destroy them and also add a part count in your game object.

but your current code there is an issue you deactivating the current player who collects the parts so when you collect the first part you deactivate the player so you won't able to collect another item.

the solution is to get the reference of the part you collecting and then make it 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;

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM