Unity3D 制作游戏简单“跑马灯”功能

前言


前言

想做一个游戏中系统消息的提示功能,于是做了一个简单的跑马灯,只实现了简单的系统文字提示功能,仅作参考


一、什么是游戏跑马灯?

在游戏内用来显示系统公告,系统消息的滚动文字显示条就是跑马灯。

二、实现

1.思路

一个滚动文本用来存放系统消息,滚动文本滚出屏幕后隐藏跑马灯。

2.代码

代码如下(示例):

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

/// <summary>
/// 跑马灯
/// </summary>
public class ViewPaoma : MonoBehaviour {

    public static ViewPaoma instance;

    public Text textInfo;

    private float speed =270;

    private float curX=0;

    private void Awake()
    {
        instance = this;
        Reset();
    }

    private void Reset()
    {
        textInfo.text = "";
        textInfo.transform.localPosition = new Vector3(Screen.width / 2, 0, 0);
        gameObject.SetActive(false);
    }

    public void Show( string _str)
    {
        textInfo.text += "     " + _str;
        curX = textInfo.transform.localPosition.x;
        gameObject.SetActive(true);
    }

    private void Update()
    {
        if(textInfo.text.Equals("") && gameObject.activeSelf)
        {
            gameObject.SetActive(false);
        }
        else
        {            
            curX -= speed * Time.deltaTime;
            float _endX = -Screen.width / 2 - textInfo.gameObject.GetComponent<RectTransform>().rect.width;
            textInfo.transform.localPosition = new Vector3(curX, 0, 0);
            if (curX< _endX)
            {
                Reset();                              
            }
        }
    }
}

效果:


总结

知识点:Content Size Fitter组件可以在文本内容改变后自动调整文本宽度

此跑马灯缺点:文本一直在增加 没有动态删减,只有全部滚动出屏幕才能清空。

其他思路:动态添加信息文本预制件来实现。

优点可以自定义信息文本颜色、字体样式、是否包含图片;可以动态隐藏、添加信息文本预制件。

猜你喜欢

转载自blog.csdn.net/leo347/article/details/125671977
今日推荐