You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Unity中LineRenderer生成新线段时删除已渲染的旧线段

问题原因

你当前的代码只使用了单个LineRenderer组件,且默认仅持有2个顶点的存储空间,每次调用Spawn_Candle方法时都会直接覆盖索引0和1的顶点坐标,之前绘制的线段数据没有被保留,所以旧线段会消失。

解决方案(连续折线方案,适配K线走势需求)

如果要保留所有历史走势线段,只需动态扩展LineRenderer的顶点数量,将新增的走势点追加到顶点列表末尾即可,修改后代码如下:

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

public class line_rend : MonoBehaviour
{
    private LineRenderer lineRend;
    float candle_y;
    public float stop_running;
    public float candle_speed;
    public float candle_delay;
    public float candle_rate;
    public float candle_volat;
    float candle_x;
    // Start is called before the first frame update
    void Awake()
    {
        candle_y = Random.Range(-4.5f, 4.5f);
        lineRend = GetComponent<LineRenderer>();
        candle_x = -11.0f;
        // 初始化线宽和初始顶点
        lineRend.startWidth = 0.1f;
        lineRend.endWidth = 0.1f;
        lineRend.positionCount = 1;
        lineRend.SetPosition(0, new Vector3(candle_x, candle_y, 0f));
        InvokeRepeating("Spawn_Candle", candle_speed, candle_delay);
    }

    public void Spawn_Candle()
    {
        // 计算新的坐标点
        candle_y += Random.Range((0f - candle_volat), candle_volat);
        candle_x += candle_rate;
        // 扩展顶点数量,追加新的坐标点
        lineRend.positionCount += 1;
        lineRend.SetPosition(lineRend.positionCount - 1, new Vector3(candle_x, candle_y, 0f));
    }
}
可选补充方案(单根蜡烛线独立方案)

如果你需要每个K线蜡烛是独立的线段(方便后续单独选中、修改样式),可以提前做好带LineRenderer的线段预制体,每次调用Spawn_Candle时实例化一个新的预制体,设置对应两个端点的坐标即可,旧的预制体会保留在场景中不会消失。

内容的提问来源于stack exchange,提问作者Adam Bishop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:54:03