Sometimes it will work properly and sometimes it will not. The trail tends to work at the wrong time sometimes and will occasionally end up flickering on and off. It looks like Unity is struggling to put the boolean to true or false sometimes, but it doesn’t happen every time which is whats confusing me. Does anyone know what would cause this to happen? Code below:
public class Ball : MonoBehaviour
{
[SerializeField] private Transform RespawnPoint;
// config parameter
[SerializeField] KeyboardControls paddle1;
[SerializeField] float pushX = 0.1f;
[SerializeField] float pushY = 10f;
[SerializeField] float randomFactor = 0.2f;
[SerializeField] float LowRandomFactor = -0.2f;
Ball ball;
TrailRenderer MyBallTrail;
// cached component references
Vector2 paddleToTheBall;
Rigidbody2D rb;
private bool hasStarted = false;
/* Variables over */
private void Awake()
{
hasStarted = false;
}
void Start()
{
paddleToTheBall = transform.position - paddle1.transform.position;
// rigidbody to rb
rb = GetComponent<Rigidbody2D>();
MyBallTrail = GetComponent<TrailRenderer>();
}
// Update is called once per frame
void Update()
{ // ball lock & stick
if (!hasStarted)
{
LockBallToPaddle();
LaunchOnClick();
}
}
public void LaunchOnClick()
{
if (Input.GetKeyDown("space"))
{
hasStarted = true;
GetComponent<Rigidbody2D>().velocity = new Vector2(pushX, pushY);
MyBallTrail.enabled = MyBallTrail.enabled;
}
else if (hasStarted == false) {
MyBallTrail.enabled = !MyBallTrail.enabled;
}
}
public void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlePos + paddleToTheBall;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 velocityAdjustment = new Vector2
//X axis
(Random.Range(LowRandomFactor,randomFactor),
//Y axis
Random.Range(0, randomFactor));
if (hasStarted)
{
MyBallTrail.enabled = MyBallTrail.enabled;
rb.velocity += velocityAdjustment;
}
}
public void ResetPosition()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
hasStarted = false;
transform.position = paddlePos + paddleToTheBall;
}
}
EDIT: I have went into debug.logging this problem and checked on the boolean. The boolean is switching fine, but the trail will not re-enable.
I am disabling it with:
private void TrailDisable()
{
MyBallTrail.enabled = !MyBallTrail.enabled;
}
I am Enabling it with:
else if (hasStarted)
{
MyBallTrail.enabled = MyBallTrail.enabled;
}