- Home /
Question by
rajarshidas24 · Oct 28, 2018 at 03:37 PM ·
scripting problemcoroutinesonmousedown
How to run the Coroutine of one script in another using the onMouseDown function ?
I am really new to c sharp. So can anyone please help me. I tried to fix this in every possible way but couldn't find any suitable answer. Thank you. Script 1:
public class DrawA : MonoBehaviour
{
[SerializeField]
public LineRenderer lineRenderer;
public Transform one;
public Transform two;
public void Start()
{
lineRenderer = gameObject.GetComponent<LineRenderer>();
lineRenderer.SetWidth(.30f, 0.30f);
one.position = GameObject.Find("point1").transform.position;
two.position = GameObject.Find("point2").transform.position;
}
public IEnumerator LineDraw()
{
float t = 0;
float time = 2;
Vector3 orig = one.position;
Vector3 orig2 = two.position;
lineRenderer.SetPosition(1, orig);
Vector3 newpos;
for (; t < time; t += Time.deltaTime)
{
newpos = Vector3.Lerp(orig, orig2, t / time);
lineRenderer.SetPosition(1, newpos);
yield return null;
}
lineRenderer.SetPosition(1, orig2);
}
}
Script 2 :(Where i want to use the coroutine of Script 1.
public class clickPointA : MonoBehaviour
{
public void OnMouseDown()
{
//i want to call the coroutine here.
}
}
Comment
Best Answer
Answer by Atiyeh123 · Oct 28, 2018 at 03:51 PM
Hi , you can do it in some ways due to your code the common way in most cases is using a public reference to the script
public class clickPointA : MonoBehaviour
{
public clickPointB clickPoint;
public void OnMouseDown()
{
//i want to call the coroutine here.
clickPoint.DrawLine();
}
}
the second code:
public class DrawA : MonoBehaviour
{
[SerializeField]
public LineRenderer lineRenderer;
public Transform one;
public Transform two;
public void Start()
{
lineRenderer = gameObject.GetComponent<LineRenderer>();
lineRenderer.SetWidth(.30f, 0.30f);
one.position = GameObject.Find("point1").transform.position;
two.position = GameObject.Find("point2").transform.position;
}
public void DrawLine()
{
StartCoroutine(LineDraw());
}
public IEnumerator LineDraw()
{
float t = 0;
float time = 2;
Vector3 orig = one.position;
Vector3 orig2 = two.position;
lineRenderer.SetPosition(1, orig);
Vector3 newpos;
for (; t < time; t += Time.deltaTime)
{
newpos = Vector3.Lerp(orig, orig2, t / time);
lineRenderer.SetPosition(1, newpos);
yield return null;
}
lineRenderer.SetPosition(1, orig2);
}
}
you can attach the script to the public var from editor
Answer by hameed-ullah-jan · Oct 29, 2018 at 05:19 AM
you can do it like this:
public class clickPointA : MonoBehaviour { public DrawA clickPoint; // declare the object of the drawA class public void OnMouseDown() { //i want to call the coroutine here. clickPoint.DrawLine(); }
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612181117im_/https://answers.unity.com/themes/thub/images/avi.jpg)