玩家得分未在TextMeshPro组件上更新

问题描述

我刚刚创建了一个TextMeshPro文本组件,然后立即从中创建了一个PreFab。然后,我将该预制件附加到脚本上(通过在序列化字段中拖动它),在此砖被销毁的位置,在此我通过.text属性更新文本。

当我Debug.Log()score.text时,它给了我正确的值。但是UI上的分数仍然为0。没有出现任何错误,我已经多次交叉检查代码

代码如下:

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class BlockScript : MonoBehavIoUr
{
    [Serializefield] TextMeshProUGUI scoreText;
    [Serializefield] LevelScript levelScript;
    [Serializefield] AudioClip clip;
    static int gamescore;
    private void Start()
    {
        gamescore = 0;
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // PlayClipAtPoint creates a temporary gameObject that is created in the world space so that
        // the sound keeps on playing even though the gameobject is deleted or destroyed
        AudioSource.PlayClipAtPoint(clip,Camera.main.transform.position);
        gamescore += 83;
        scoreText.text = gamescore.ToString();
        Destroy(gameObject);        
        Debug.Log("Object name: " + collision.gameObject.name);
        Debug.Log("Gamescore: " + gamescore);
        Debug.Log("Frame Count: " + Time.frameCount);       
        Debug.Log(scoreText.text);
    }
}

日志:

Object name: Ball
UnityEngine.Debug:Log(Object)
 
Gamescore: 83
UnityEngine.Debug:Log(Object)
 
Frame Count: 162
UnityEngine.Debug:Log(Object)
 
Object name: Ball
UnityEngine.Debug:Log(Object)
 
Gamescore: 166
UnityEngine.Debug:Log(Object)
 
Frame Count: 337
UnityEngine.Debug:Log(Object)

我还注意到,只能将预制件拖到预制件的序列化字段上,而不能拖动到普通游戏对象上。请帮我解决这个问题,如果您需要任何其他信息,请告诉我。

在下面所附的图像上,您还可以看到我停止玩游戏后,分数显示为747。但是在游戏过程中,分数为0。

因此,总的来说,分数不会在玩游戏时更新,而只有在我停止播放按钮后才能看到最终分数。

UI:

Unity Editor UI

解决方法

所以这里的问题是不好的参考。

该引用不是指向场景Score物体,而是指向Editor预制件,而不是当前在场景中实例化的那个。

一种快速解决方案:

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class BlockScript : MonoBehaviour
{
    [SerializeField] TextMeshProUGUI scoreText;
    [SerializeField] LevelScript levelScript;
    [SerializeField] AudioClip clip;
    static int gameScore;
    private void Start()
    {
        gameScore = 0;
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // PlayClipAtPoint creates a temporary gameObject that is created in the world space so that
        // the sound keeps on playing even though the gameobject is deleted or destroyed
        AudioSource.PlayClipAtPoint(clip,Camera.main.transform.position);
        gameScore += 83;

        //Find the scene reference
        scoreText = GameObject.FindGameObjectWithTag("ScoreText");
        
        scoreText.text = gameScore.ToString();

        Debug.Log("Object name: " + collision.gameObject.name);
        Debug.Log("GameScore: " + gameScore);
        Debug.Log("Frame Count: " + Time.frameCount);       
        Debug.Log(scoreText.text);

        Destroy(gameObject);                
    }
}

另一种避免使用FindByTag方法(昂贵的方法)的方法是简单地将Score游戏对象拖放到块scoreText变量中。