I am trying to find out how I would draw a line between 2 diffrent gameObjects.
I assume the Line Renderer is what i need to use…but I don’t know how to implement it.
I basicallty want to draw a line from the tip of a “gun” to the “projectile”. so the line would grow/shrink according to the position of both the projectile and the tip of the gun.
Can someone help me understand how to achive this?
Maybe the Line Renderer is not the way to go, i don’t know.
private void SomeFunction()
{
var go = new GameObject();
var lr = go.AddComponent<LineRenderer>();
var gun = GameObject.Find("Gun");
var projectile = GameObject.Find("Projectile");
lr.SetPosition(0, gun.transform.position);
lr.SetPosition(1, projectile.transform.position);
}
Not efficient code or good coding practices, just an example. All you really need to know about is the SetPosition function.
If you’re projectile is moving, you’ll need to update the position every Update().
I wrote a script that does something similar a week ago, because I can’t believe that Unity is actually missing the functionality of drawing a line between 2 objects.
Generating the gameobject/line renderer on the fly isn’t good for garbage collecting. Especially from a gun where you’d likely have to keep generating/destroying them quite frequently. Should pool them.
Also shouldn’t search for gun/projectile everytime, rather have a reference.
Oh I figured it was something like that. In my case you pass in the references, I was doing a rotatable upgrade menu with lines that point to text that float coming off the object you can upgrade.
It took me an hour or research to discover the answer: Come on guys, just give a straight answer if you can.
Here’s the tutorial that helps with setting up an empty gameObject, make the laser material, etc.
Once you know it’s not a mystery.
Here’s the basics you need to know to make it happen.
private var line : LineRenderer;
var origin : Transform;
var destin : Transform;
function Start() {
line=GetComponent(LineRenderer);
line.SetWidth(.2f , .2f); // or just set it in the Inspector
}
function Update() {
line.SetPosition(0, origin.position);
line.SetPosition(1, destin.position);
}