Добавить количество бомб, когда игрок сталкивается не работает - PullRequest
0 голосов
/ 02 ноября 2018

Я пытался использовать панель поиска перед публикацией, но ничего, что я нашел, на самом деле не решило мою проблему.

Когда игрок проходит через «Предмет», он уходит, как и ожидалось, однако я также хочу, чтобы он добавил одну бомбу к игрокам, имеющим номер 0, когда предмет тоже поднят, но, похоже, это не так. за работой? Любая помощь с благодарностью.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class shooter : MonoBehaviour
{
public GameObject powercell; //link to the powerCell prefab
public int no_cell = 1; //number of powerCell owned
public AudioClip throwSound; //throw sound
public float throwSpeed = 20;//throw speed
                             // Update is called once per frame
public void Update()
{
    //if left control (fire1) pressed, and we still have at least 1 cell
    if (Input.GetButtonDown("Fire1") && no_cell > 0)
    {
        no_cell--; //reduce the cell
                   //play throw sound
        AudioSource.PlayClipAtPoint(throwSound, transform.position);
        //instantaite the power cel as game object
        GameObject cell = Instantiate(powercell, transform.position,
        transform.rotation) as GameObject;
        //ask physics engine to ignore collison between
        //power cell and our FPSControler
        Physics.IgnoreCollision(transform.root.GetComponent<Collider>(),
        cell.GetComponent<Collider>(), true);
        //give the powerCell a velocity so that it moves forward
        cell.GetComponent<Rigidbody>().velocity = transform.forward * throwSpeed;
    }
}

//
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Item")
    {
        no_cell = 1;
        Destroy(gameObject);
    }
}

// Use this for initialization
void Start()
{

}
}

Ответы [ 2 ]

0 голосов
/ 02 ноября 2018

Сначала измените ваш скрипт на следующий. Если вы по-прежнему не видите увеличения no_cell в консоли, сделайте несколько снимков экрана из своего редактора, где показан сценарий, прикрепленный к игровому объекту, и место, где вы ожидаете увидеть разницу.

public class shooter : MonoBehaviour {
    public GameObject powercell;    //link to the powerCell prefab
    public int no_cell ;            //number of powerCell owned
    public AudioClip throwSound;    //throw sound
    public float throwSpeed = 20;   //throw speed

    // Use this for initialization
    void Start(){
        no_cell = 1;
    }

    // Update is called once per frame
    public void Update()
    {
        //if left control (fire1) pressed, and we still have at least 1 cell
        if (Input.GetButtonDown("Fire1") && no_cell > 0)
        {
            no_cell--; //reduce the cell
                       //play throw sound
            AudioSource.PlayClipAtPoint(throwSound, transform.position);
            //instantaite the power cel as game object
            GameObject cell = Instantiate(powercell, transform.position,
            transform.rotation) as GameObject;
            //ask physics engine to ignore collison between
            //power cell and our FPSControler
            Physics.IgnoreCollision(transform.root.GetComponent<Collider>(),
            cell.GetComponent<Collider>(), true);
            //give the powerCell a velocity so that it moves forward
            cell.GetComponent<Rigidbody>().velocity = transform.forward * throwSpeed;
        }
    }


    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Item")
        {
            no_cell++;              
            Debug.Log("Number of cells:"+no_cell.ToString());
            Destroy(other);
        }
    }


}
0 голосов
/ 02 ноября 2018

Если я правильно понял, каждый раз, когда вы сталкиваетесь с «Предметом», вы хотите добавить 1 дополнительную клетку? Затем вы должны перейти no_cell ++ (или оставить его как есть, если ваш максимальный no_cell должен быть 1).

Кроме того, проверьте, уменьшает ли ваше состояние no_cell другое условие, поэтому, возможно, по этой причине вы не видите, что оно увеличивается.

Наконец, совет подсказки - использовать Start () для инициализации (например, no_cell = 1), и если no_cell ссылается на количество ячеек, тогда используйте удобное именование ближе к естественному языку, например, cellNumber.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...