using System.Collections.Generic; using UnityEngine; namespace MoreMountains.Tools { /// /// This component, added to a line renderer, will let you fill a list of transforms, and bind their positions to the /// linerenderer's positions. /// [RequireComponent(typeof(LineRenderer))] public class MMLineRendererDriver : MonoBehaviour { [Header("Position Drivers")] /// the list of targets - their quantity has to match the LineRenderer's positions count public List Targets; /// whether or not to keep both in sync at update public bool BindPositionsToTargetsAtUpdate = true; [Header("Binding")] /// a test button [MMInspectorButton("Bind")] public bool BindButton; protected bool _countsMatch; protected LineRenderer _lineRenderer; /// /// On Awake we initialize our driver /// protected virtual void Awake() { Initialization(); } /// /// On Update we bind our positions to targets if needed /// protected virtual void Update() { if (BindPositionsToTargetsAtUpdate) BindPositionsToTargets(); } /// /// Grabs the line renderer, tests counts /// protected virtual void Initialization() { _lineRenderer = gameObject.GetComponent(); _countsMatch = CheckPositionCounts(); if (!_countsMatch) Debug.LogWarning(name + ", MMLineRendererDriver's Targets list doesn't have the same amount of entries as the LineRender's Positions array. It won't work."); } /// /// A method meant to be called by the inspector button /// protected virtual void Bind() { Initialization(); BindPositionsToTargets(); } /// /// Goes through all the targets and assigns their positions to the LineRenderer's positions /// public virtual void BindPositionsToTargets() { if (!_countsMatch) return; for (var i = 0; i < Targets.Count; i++) _lineRenderer.SetPosition(i, Targets[i].position); } /// /// Makes sure the counts match /// /// protected virtual bool CheckPositionCounts() { return Targets.Count == _lineRenderer.positionCount; } } }