Why Does my bool turns true even after its supposed to be false?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YonduArrowBullet : MonoBehaviour
{
//public GameObject Body;

public Transform RocketTarget;
public Rigidbody RocketRig;

public float turnSpeed = 1f;
public float rocketFlySpeed = 10f;

public int maxHits = 10;
int hit = 0;

float originalTime;

public float timeToShoot = -1.3f;

public AudioSource EnemySorce;
public AudioClip flyingEnemySound;

//GameObject Player;
bool backToPlayer;

public bool back = false;

private Transform rocketLocalTrans;
// Start is called before the first frame update
public void Start()
{
    
    back = false;
    EnemySorce = GetComponent<AudioSource>();

   
    originalTime = timeToShoot;

    if (!RocketTarget)
        Debug.Log("Please set target");

    rocketLocalTrans = GetComponent<Transform>();

    
}

// Update is called once per frame
public void FixedUpdate()
{

    timeToShoot -= Time.deltaTime;

	if (backToPlayer)
	{
        RocketTarget = GameObject.FindWithTag("Player").transform;

    }
	else
	{
         RocketTarget = GameObject.FindWithTag("OneShot").transform;
	}
    
     //Player = GameObject.FindWithTag("Player").transform;

    RocketRig.velocity = rocketLocalTrans.forward * rocketFlySpeed;

    var rocketTargetRot = Quaternion.LookRotation(RocketTarget.position - rocketLocalTrans.position);

    RocketRig.MoveRotation(Quaternion.RotateTowards(rocketLocalTrans.rotation, rocketTargetRot, turnSpeed));

    

}

public void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == “OneShot”)
{EnemySorce.PlayOneShot(flyingEnemySound);
hit++;

       if (RocketTarget == null)
        Destroy(gameObject);

       if(hit >= maxHits)
		{

            backToPlayer = true;
        }

        if (timeToShoot < 0)
        {

            backToPlayer = true;
        }

       
    }
    
    if (collision.gameObject.tag == "Player")
    {  
            
        back = true;
        //Body.SetActive(true);
        Destroy(gameObject);
    }
}

}

1 Answer

1

So I see a few problems.

timeToShoot is always less then 0 thus backToPlayer always gets set to true. You are also subtracting deltatime from timeToShoot making it a bigger and bigger negative number. Also nothing sets backToPlayer to false except for the initial value.

You also set bool back to false, then to false again in Start(). The first time back gets set to true, it stays true forever because the only thing that turns it false is inside Start().