using UnityEngine;
public class DeleteProjectile : MonoBehaviour
{
[SerializeField] private GameObject player;
private float projectileSpeed;
private Vector3 projectileDirection;
// I'm assuming your bullet is detached from the player and I've added getcomponents and a serialized player gameobject field for you to fill.
private void Start()
{
PlayerSpeedScript speedScript = player.GetComponent<PlayerSpeedScript>(); // Replace all PlayerSpeedScript with whichever script your speed is in.
projectileSpeed = speedScript.projectileSpeed;
PlayerDirectionScript directionScript = player.GetComponent<PlayerDirectionScript>(); // Replace all PlayerDirectionScript with whichever script your direction is in.
projectileDirection = directionScript.projectileDirection;
}
// You could also add a float speed/vector3 direction requirement to this function and fill it wherever you spawn the projectile, eg private void RaycastTimeToDestroyProjectile(float speed, Vector3 direction)
private void RaycastTimeToDestroyProjectile()
{
if (Physics.Raycast(transform.position, projectileDirection, out RaycastHit hit, Mathf.Infinity, wallLayerMask))
{
Debug.DrawRay(transform.position, projectileDirection * hit.distance, Color.yellow, 0.5f); // Debugging raycaster
float distance = Vector3.Distance(transform.position, hit.point);
float time;
// Generates a time to delete, to 2 decimal places, if you need more accuracy, change how this works.
time = distance / Mathf.Max(projectileSpeed, 0.01f);
deleteCoroutine = StartCoroutine(DeleteProjectile(time));
}
}
private IEnumerator DeleteProjectile(float time)
{
yield return new WaitForSeconds(time);
Destroy(gameObject); // I recommend object pooling, pooling disables and re-enables projectiles instead of deleting - result is better fps and stability.
}
}