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

Unity中Scene视图可见但Game视图不可见,LineRenderer绘图问题求助

问题:Scene视图可见绘制线条,但Game视图无法显示

我在Scene视图中能看到绘制的线条,但在Game视图里看不到。希望在Game视图中显示线条,验证功能是否正常。

Scene视图可见线条,Game视图不可见

代码上下文

public class tapLine : MonoBehaviour
{
    public LineRenderer lineRenderer;

    private bool isDrawing = false;
    private Vector3 startPoint;

    private void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            if (touch.phase == TouchPhase.Began)
            {
                StartDrawing(touch.position);
            }
            else if (touch.phase == TouchPhase.Moved && isDrawing)
            {
                UpdateDrawing(touch.position);
            }
            else if (touch.phase == TouchPhase.Ended && isDrawing)
            {
                EndDrawing();
            }
        }
    }

    private void StartDrawing(Vector3 startPos)
    {
        isDrawing = true;
        startPoint = Camera.main.ScreenToWorldPoint(startPos);
        lineRenderer.positionCount = 1;
        lineRenderer.SetPosition(0, startPoint);
    }

    private void UpdateDrawing(Vector3 currentPos)
    {
        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(currentPos);
        lineRenderer.positionCount = 2;
        lineRenderer.SetPosition(1, worldPosition);
    }

    private void EndDrawing()
    {
        isDrawing = false;
        lineRenderer.positionCount = 0;
    }
}

解决方法

  • 修正屏幕坐标转世界坐标的Z轴值:ScreenToWorldPoint需要明确Z轴深度(相对于相机的距离),否则生成的点会和相机重叠导致不可见。修改StartDrawing和UpdateDrawing方法:
    private void StartDrawing(Vector3 startPos)
    {
        isDrawing = true;
        // 添加Z轴深度,确保线条在相机可视范围内
        Vector3 screenPosWithDepth = new Vector3(startPos.x, startPos.y, Camera.main.nearClipPlane + 1f);
        startPoint = Camera.main.ScreenToWorldPoint(screenPosWithDepth);
        lineRenderer.positionCount = 1;
        lineRenderer.SetPosition(0, startPoint);
    }
    
    private void UpdateDrawing(Vector3 currentPos)
    {
        Vector3 screenPosWithDepth = new Vector3(currentPos.x, currentPos.y, Camera.main.nearClipPlane + 1f);
        Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosWithDepth);
        lineRenderer.positionCount = 2;
        lineRenderer.SetPosition(1, worldPosition);
    }
    
  • 检查LineRenderer的材质与颜色:确保LineRenderer使用的材质不透明,颜色Alpha值不为0,可直接使用Unity内置的Sprites/Default材质测试。
  • 确认相机Culling Mask:检查相机的Culling Mask是否包含LineRenderer所在的层(默认是Default层,不要排除该层)。
  • 调整线条宽度:确保LineRenderer的Start Width和End Width设置为大于0的值(例如0.1),避免因宽度为0导致不可见。

内容的提问来源于stack exchange,提问作者Aloera Polk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:07:11