Skip to content

Instantly share code, notes, and snippets.

@takashi1975
Created July 23, 2019 00:14
Show Gist options
  • Save takashi1975/888cada7257052b79672003b4bf32052 to your computer and use it in GitHub Desktop.
Save takashi1975/888cada7257052b79672003b4bf32052 to your computer and use it in GitHub Desktop.
Unity LineRender (マウスで線を描く)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* https://unitycoder.com/blog/2017/08/27/drawing-lines/
*
* Unity ver.2018.3.13f1 で確認
*/
public class DrawLine : MonoBehaviour {
[field: SerializeField]
public LineRenderer lineRenderer { get; private set; }
[field: SerializeField]
public Camera camera { get; private set; }
[field: SerializeField]
public List<Vector3> points { get; private set; }
private void Awake() {
if (this.lineRenderer == null) {
Debug.LogWarning("DrawLine: Line Renderer not assigned, Adding and Using default Line Renderer.");
this.lineRenderer = this.CreateDefaultLineRenderer();
}
if (this.camera == null) {
Debug.LogWarning("DrawLine: Camera not assigned, Using Main Camera or Creating Camera if main not exists.");
this.camera = this.CreateDefaultCamera();
}
this.points = new List<Vector3>();
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
this.Reset();
}
if (Input.GetMouseButton(0)) {
var mousePosition = this.camera.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = this.lineRenderer.transform.position.z;
if ( !this.points.Contains(mousePosition)) {
this.points.Add(mousePosition);
this.lineRenderer.positionCount = this.points.Count;
this.lineRenderer.SetPosition(this.lineRenderer.positionCount - 1, mousePosition);
}
}
}
protected virtual void Reset() {
if (this.lineRenderer != null) {
this.lineRenderer.positionCount = 0;
}
if (this.points != null) {
this.points.Clear();
}
}
protected virtual LineRenderer CreateDefaultLineRenderer() {
var renderer = this.gameObject.AddComponent<LineRenderer>();
renderer.positionCount = 0;
renderer.material = new Material(Shader.Find("Mobile/Particles/Additive"));
renderer.startColor = Color.white;
renderer.endColor = Color.white;
renderer.startWidth = 0.3f;
renderer.endWidth = 0.3f;
renderer.useWorldSpace = true;
return renderer;
}
protected virtual Camera CreateDefaultCamera() {
var camera = Camera.main;
if (camera == null) {
camera = this.gameObject.AddComponent<Camera>();
}
if (camera != null) {
camera.orthographic = true;
}
return camera;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment