Unity_使用Image和脚本生成虚线段

生成如图样式的虚线段

原理:使用Image做一条线段,这个方法的原理就是给固定的片元长度,对Image进行分割,把片元添加到一个列表中,然后循环对列表中的偶数位进行隐藏,也可以调整线段的宽度

缺陷:有曲线折线的时候,要对每个片元再做旋转位移等操作,且效果不太理想,所以对直线最方便

代码如下:

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

public class DashLineDraw : MonoBehaviour
{
    public static DashLineDraw _dashlineInstance;
    public Image TargetWellWidth;//井径
    public Image TargetWellPosition;//方位
    public Image TargetWellincline;//井斜

    public int WidthpieceLength,inclineLength;//固定线的片元长度

    private void Awake()
    {
        _dashlineInstance = this;
        WidthpieceLength = 5;
        inclineLength = 10;

        DashLine(TargetWellWidth, WidthpieceLength);
        //DashLine(TargetWellPosition, WidthpieceLength);
        //DashLine(TargetWellincline, inclineLength);
    }
   
    /// 
    /// 画虚线
    /// 
    /// 
    /// 
    public void DashLine(Image targetpic,int pieceLength)
    {
        int pieceNum;//片元数量
        ListpieceList = new List();
        RectTransform targetRect;
        targetRect = targetpic.GetComponent();

        float offsetLineX = (targetRect.sizeDelta.x) / 2;
        pieceNum = (int)((targetpic.GetComponent().rect.width) / pieceLength);
        RectTransform firstRectTransform = null;
        
        for (int i = 0; i < pieceNum; i++)
        {
            Image pieceImage = Instantiate(targetpic, transform);
            RectTransform pieceRectTransform = pieceImage.rectTransform;

            if (i == 0)
            {
                pieceRectTransform.sizeDelta = new Vector2(pieceLength, 2);
                pieceRectTransform.anchoredPosition = new Vector2(targetRect.anchoredPosition.x - offsetLineX + (pieceLength / 2), targetRect.anchoredPosition.y);
                firstRectTransform = pieceRectTransform;
            }
            else
            {
                pieceRectTransform.sizeDelta = new Vector2(pieceLength, 2);
                pieceRectTransform.anchoredPosition = new Vector2(firstRectTransform.anchoredPosition.x + (pieceLength * i), firstRectTransform.anchoredPosition.y);
            }
            pieceList.Add(pieceImage.gameObject);
        }
        targetpic.GetComponent().enabled = false;
        for (int i = 0; i < pieceList.Count; i++)
        {
            if ((i + 1) % 2 == 0)
            {
                // 偶数
                pieceList[i].GetComponent().enabled = false;
            }
        }
    }
}

Unity_使用Image和脚本生成虚线段_第1张图片

通过调整Length对宽度调整。

你可能感兴趣的:(C#,游戏开发,Unity引擎,unity,游戏引擎)