In Unity I need my TrailRenderer's trail to not stay behind the moving parent's object,…
- User
In Unity I need my TrailRenderer's trail to not stay behind the moving parent's object, so it doesn't leave trail behind, but stays in local space. I need code for that
- Assistant
To keep the TrailRenderer's trail in local space, you can use the following code:
public class LocalTrailRenderer : MonoBehaviour { private TrailRenderer trailRenderer; private void Start() { trailRenderer = GetComponent<TrailRenderer>(); } private void LateUpdate() { trailRenderer.Clear(); trailRenderer.AddPosition(transform.localPosition); } }This script should be attached to the same object as the TrailRenderer component. It will clear the previous positions in the trail and only add the local position of the parent object in the LateUpdate function, which ensures that the position is updated every frame after the parent object has moved. This will make the trail stay in local space and not leave a trail behind.
- User
But I don't whant it to clear every frame
- Assistant
If you don't want to clear the positions in the trail every frame, you can modify the code and add a boolean flag to control when to clear the trail. Here's the updated code:
public class LocalTrailRenderer : MonoBehaviour { private TrailRenderer trailRenderer; private bool clearTrail = false; // Flag to control when to clear the trail private void Start() { trailRenderer = GetComponent<TrailRenderer>(); } private void LateUpdate() { if (clearTrail) { trailRenderer.Clear(); // Clear the trail if the flag is set clearTrail = false; // Reset the flag } trailRenderer.AddPosition(transform.localPosition); // Add the local position to the trail } // Call this function to clear the trail public void ClearTrail() { clearTrail = true; } }