So im trying to make a gun script, and this is the script that is attatched to the bullet. My issue, is that when the bullet hits an enemy, it does not set "hashit" to true. It does detect the collision however.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bulletSelf : MonoBehaviour
{
bool original = true;
[Header("The speed of the bullet moving forward")]
public float speed;
[Header("Do you want the bullet to despawn after a certain amount of time")]
public bool Despawn;
[Header("Time before the bullet despawns")]
public float TimeToDespawn;
[Header("To detect if this is the original bullet- Dont Change")]
public OBG obg;
[Header("Set this variable to itself")]
public GameObject thisBullet;
[Header("All tags attatched to enemy")]
public List AllEnemyTags;
[Header("The time after the bullet hits an enemy before it despawns (recommended 0)")]
public float TimeAfterHit;
bool hasHit;
public void Start()
{
if(thisBullet == obg.originalbullet)
{
original = true;
} else
{
original = false;
}
hasHit = false;
}
public void OnCollisionEnter(Collision collision)
{
Debug.Log("collision detected");
foreach (string tag in AllEnemyTags)
{
Debug.Log(tag + " found");
if (collision.gameObject.CompareTag(tag))
{
Debug.Log("collision detected with" + collision.gameObject.name);
if (TimeAfterHit == 0)
{
Debug.Log("No time is there!");
Destroy(thisBullet.gameObject);
}
Debug.Log("Setting hashit");
hasHit = true;
}
}
}
void Update()
{
if (hasHit == true)
{
Debug.Log("hashit is true");
if (TimeAfterHit > 0)
{
Debug.Log("Hashit greater than zero, subtracting");
TimeAfterHit = TimeAfterHit - Time.deltaTime;
}
if (TimeAfterHit < 0)
{
Debug.Log("Hashit less than zero, setting to zero");
TimeAfterHit = 0;
}
if (TimeAfterHit == 0)
{
Debug.Log("destroying");
Destroy(thisBullet.gameObject);
}
}
if (original == false)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
if (Despawn == true)
{
TimeToDespawn = TimeToDespawn - Time.deltaTime;
if (TimeToDespawn < 0)
{
TimeToDespawn = 0;
}
if (TimeToDespawn == 0)
{
Destroy(thisBullet.gameObject);
}
}
}
}
}
Here is what the console logs say:
Collision Detected
Enemy Found
Collsiion detected withEnemy
setting hashit
Then nothing else; after that it SHOULD have set hashit to true, but it doesent
↧