- Home /
Get line Renderer code to restart animation every time mouse is clicked
So I have a line that appears in front of my player to provide directional assistance. It animates by moving from one game object to another (positioned in front of parent gameObject(player).
This works fine on the first click however any click afterwards only shows the rendered line at full height and doesn't animate the line.
How do I get the script below to repeat/ restart every time its clicked?
any help would be greatly appreciated I'm still in my noob faze :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbitAssist : MonoBehaviour {
LineRenderer link;
public Transform[] pos;
public float speed;
// Start is called before the first frame update
void Start()
{
link = gameObject.GetComponent<LineRenderer> ();
}
// Update is called once per frame
public void Update()
{
{
if (Input.GetMouseButton (0))
{
//how to get this line of code to repeat/restart on every mouse click???
gameObject.GetComponent<LineRenderer>().enabled = true;
link.SetPosition(0, pos[0].position);
link.SetPosition(1, Vector3.MoveTowards (transform.position,pos[1].position,speed *Time.time));
}
if (Input.GetMouseButtonUp (0))
{
gameObject.GetComponent<LineRenderer>().enabled = false;
link.SetPosition(0, pos[0].position);
}
}
}
}
Answer by swanne · Nov 03, 2020 at 11:11 AM
Hey,
I recommend having a look into using coroutines. On the mouse click set your link enabled to true and then run the coroutine to draw the line and set link enabled to false.
hey thanks for getting back. Are you able to give an example?
I tried to create a coroutine but when i start my unity project its freezes and i have to force close it down?!
LineRenderer link; public Transform[] pos;
public float speed;
// Start is called before the first frame update
void Start () {
}
IEnumerator Path()
{
while (true) {
gameObject.GetComponent<LineRenderer>().enabled = true;
link.SetPosition(0, pos[0].position);
link.SetPosition(1, Vector3.$$anonymous$$oveTowards (transform.position,pos[1].position,speed *Time.time));
}
}
IEnumerator NoPath()
{
while (true) {
gameObject.GetComponent<LineRenderer>().enabled = false;
link.SetPosition(0, pos[0].position);
}
}
private void FixedUpdate()
{
link = gameObject.GetComponent<LineRenderer> ();
if (Input.Get$$anonymous$$ouseButton (0))
{
StartCoroutine (Path());
}
if (Input.Get$$anonymous$$ouseButtonUp (0))
{
StartCoroutine (NoPath());
}
}
}