I am using a trail renderer in my game and sometimes I need to reset the position of my object.
Is there a way to update positions of trail, so i can preserve the trail after I change the position of object.
PS. I don’t want to clear the renderer.
1 do a .SetActive(false) on the root game object (assuming the trail renderer is somewhere in that hierarchy)
2 move the object to a new location
3 do a .SetActive(true) on it
If that doesn’t work, then maybe do instead of the above:
1 - same as above
2 move the object to the tail of its trail renderer
3 do a .SetActive(true) on it
4 move it forward to its final location
Thats what I was thinking. The waves are a child of the boat object. So you need to move the waves so that they are not a child anymore. then destroy the boat. or even better, copy the wave to a new object, then move the boat and original wave to a new location.
gameObject.SetActive(false);
transform.position = new Vector3(transform.position.x, 0, 0);
gameObject.SetActive(true);
gameObject.SetActive(false);
transform.position = new Vector3(transform.position.x, 0, -5);
transform.position = new Vector3(transform.position.x, 0, 0);
gameObject.SetActive(true);
The problem here is probably, as it stated in documents, trail renderer needs to “laid out over a sequence of frames”. But there should be an option to just assign vertices by code to move the trail.
Ah well, sorry to lead you astray. You might want to do your own trail renderer using the LineRenderer component and driving your own historical vertex positions.
That way when you reposition the object, you can instantly reposition all the verts in your line renderer and have complete control.
If you’re unfamiliar with the LineRenderer, it also has a boolean that specifies if it uses world coordinates. You might be able to say “uses local coordinates” and then the act of moving it will also move the rendered output automagically. Obviously if you use it in this mode, you would need to feed in local coordinates (relative to the transform it is on) to get the right effect.
I tried that snippet, but it clears the trail when teleporting the ship, so it didn’t solve my problem: I want to instantly teleport my ship with its trail, so that the player doesn’t even know that happened. Luckily, I found out that you can edit the trail vertices, so this works perfectly for me:
var newPosition = new Vector3(50, 10, 31); //arbitrary
var offset = newPosition - transform.position;
var trailRenderers = GetComponentsInChildren<TrailRenderer>();
foreach (var trailRenderer in trailRenderers)
{
var positionCount = trailRenderer.positionCount;
for (var i=0; i<positionCount; i++)
trailRenderer.SetPosition(i, trailRenderer.GetPosition(i) + offset);
}
transform.position = newPosition;