The code below, when attached to any gameObject, like a cube, is meant to move it around using the WASD keys and create a trail line behind it while holding the F button down. Creating the first line works fine but for some reason attempting to create a second line causes weird Assertion Failed errors and the line gets rendered at seemingly random places.
The errors I’m getting (which are repeated numerous times in the console):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LinerendererTest : MonoBehaviour {
public float movementSpeed = 0.1f;
LineRenderer currentLine;
int numPoints;
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.F))
{
GameObject newLine = new GameObject();
currentLine = newLine.AddComponent<LineRenderer>();
currentLine.startWidth = 0.1f;
currentLine.endWidth = 0.1f;
}
else if (Input.GetKey(KeyCode.F))
{
currentLine.numPositions = numPoints + 1;
currentLine.SetPosition(numPoints, transform.position);
numPoints++;
}
//Movement
if (Input.GetKey(KeyCode.W))
{
transform.Translate(transform.forward * movementSpeed);
}
if (Input.GetKey(KeyCode.D))
{
transform.Translate(transform.right * movementSpeed);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(-transform.forward * movementSpeed);
}
if (Input.GetKey(KeyCode.A))
{
transform.Translate(-transform.right * movementSpeed);
}
if (Input.GetKey(KeyCode.Space))
{
transform.Translate(transform.up * movementSpeed);
}
if (Input.GetKey(KeyCode.LeftShift))
{
transform.Translate(-transform.up * movementSpeed);
}
}
}
You can recreate this issue by copying the script above and adding it to a primitive cube game object. Move the cube around using WASD, and at the same time press and hold F to create lines behind the cube as you move it. You’ll notice that the bug happens the second time you create the line.
Any prompt help would be really appreciated.