【问题标题】:Script stops counting after 1 count脚本在 1 次计数后停止计数
【发布时间】:2017-12-29 04:00:03
【问题描述】:

我开始练习 Unity 和 c# 已经 4-5 天了。我很业余。我有一个我无法弄清楚的问题。我正在尝试编写类似 2D 乒乓球的简单游戏。每次球员错过球时,我都会实例化球并计算得分。但是即使每次都实例化球,游戏也会在1次后停止增加分数。

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

public class ballmove : MonoBehaviour
{
    private Rigidbody2D rb;
    public float speed;
    public GameObject top;
    private Vector2 direct;
    public int p2;
    public int p1;
    public Text scoretext;
    public Text scoretext2;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        speed = 3f;
        InvokeRepeating("speedUp", 10f, 10f);

        p1 = 0;
        p2 = 0;
    }

    void Update()
    {
        if (rb.velocity == new Vector2(0f, 0f))
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.velocity = new Vector2(2f, 1f) * speed;
            }
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "finish2")
        {
            Debug.Log("This if is working");

            p2++;

            Instantiate(top, new Vector2(-6.4f, -0.2f), Quaternion.identity);
            Destroy(this.gameObject);

            updateScore2();
        }
        if (other.gameObject.tag == "finish")
        {
            p1++;

            Instantiate(top, new Vector2(6.32f, -0.2f), Quaternion.identity);
            Destroy(this.gameObject);

            updateScore();
        }
    }

    void updateScore()
    {
        scoretext.text = p1.ToString();
    }
    void updateScore2()
    {
        scoretext2.text = p2.ToString();
    }
    void speedUp()
    {
        direct = rb.velocity.normalized;
        rb.velocity += direct * 2f;
    }
}

我的 p1 和 p2(分数)都增加了 1 倍。但它们与

处于相同的条件下

实例化并且每次其中一个玩家得分时,实例化工作但 p1 和/或 p2 停留在

值 1。

谢谢。

【问题讨论】:

    标签: c# unity3d counter counting


    【解决方案1】:

    我无法评论这个问题,因为我有

    如果是这样,那就是问题所在。球实例化时的分数为 0,当它被销毁时,只需将分数再次写入显示分数。

    尝试将分数的定义更改为静态:

    public static int p2;
    public static int p1;
    

    编辑: 我第一次看时错过了这个,但是,您还在 Start() 函数中将分数设置为 0。您需要删除它,而是将它们初始化为原始定义中的 0:

    public static int p2 = 0;
    public static int p1 = 0;
    

    【讨论】:

    • 我试过了。但不幸的是没有工作。顺便说一句,我创建了新的 testVar。并在 p1 附近增加并打印到控制台。有用。它增加了,但不知何故 p1 和 p2 又回到了 0。
    • 再看我的回答;起初我错过了一些东西,但我再次编辑了。我认为这应该可以为您解决。
    • 成功了。谢谢!。但为什么?不启动功能只运行 1 次?
    • 启动函数只运行一次对于每个实例。每次得分后实例化一个新球,新球会再次运行Start(),重置分数。
    • 好的,我明白了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多