首页 > 解决方案 > 在文本后显示 UnityEngine.Sprite

问题描述

这是我现在的代码:`using System.Collections;

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

public class easyModeImageSpawner : MonoBehaviour
{
    private int rand;
    private int newRand;
    private int randForButton;
    public List<Sprite> image_pic2 = new List<Sprite>();
    public List<Sprite> image_pic3 = new List<Sprite>();

    int previousresult;

    public List<TMP_Text> optionBUttonText = new List<TMP_Text>();
    private void Start()
    { 
        rand = Random.Range(0, image_pic2.Count);
        GetComponent<SpriteRenderer>().sprite = image_pic2[rand];
        //image_pic2.RemoveAt(rand);
        RandomizeText();
    }

    public void NextRound()
    {
        rand = Random.Range(0, image_pic2.Count);
     
        GetComponent<SpriteRenderer>().sprite = image_pic2[rand];
    }

    public void RandomizeText()
    {
     
        newRand = Random.Range(0, image_pic3.Count);
        randForButton = Random.Range(0, optionBUttonText.Count);
        optionBUttonText[randForButton].text = image_pic2[rand].ToString(); // over here it also 
        shows 
        UnityEngine.Sprite
        image_pic3.RemoveAt(rand);
    
        optionBUttonText.RemoveAt(randForButton);
        int i = 0;
        while (i != 3)
        {
            Debug.Log("running other button");
            newRand = Random.Range(0, image_pic3.Count);
            randForButton = Random.Range(0, optionBUttonText.Count);
            if (newRand == previousresult)
            {
               Randomize();
            }
            optionBUttonText[randForButton].text = image_pic3[newRand].ToString(); // over here it 
            also 
            shows UnityEngine.Sprite
            optionBUttonText.RemoveAt(randForButton);
        
            previousresult = newRand;
            i++;
        }
    }

    void Randomize()
    {
        newRand = Random.Range(0, image_pic3.Count);
        randForButton = Random.Range(0, optionBUttonText.Count);
    }
   }`

这是这段代码的结果: image

问题是,当您玩游戏时,按钮上的文本会显示名称,但之后还会在其上添加“Unityengine.sprite”,我正在研究,但我不确定如何解决这个问题。

我认为您必须在 ToString() 的括号中添加一些内容,但我不确定是什么。

如果有人知道如何解决这个问题,请告诉我。

提前致谢。

标签: c#unity3d

解决方案


如果您希望获得Sprite在 Hierarchy 中看到的 GameObject 的名称,请使用.nameinstead.ToString()方法。使用.ToString()方法不仅会获取游戏对象的名称,还会获取数据类型。

在您的情况下image_pic2[rand].ToString(),使用. 而不是image_pic2[rand].name.


推荐阅读