Hello, dear Unity community members!
I am trying to develop a small platformer and currently experiencing a problem with one of the enemy scripts, because the enemy does not shoot any missiles (although it is supposed to). The idea was that the enemy should be patrolling and shooting a missile every X seconds.
Thus, I wrote the following script for enemy shooting behavior:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShootingEnemyBehaviour : MonoBehaviour {
private float timeBtwShots;
public float startTimeBtwShots;
public GameObject projectile;
void Start () {
timeBtwShots = startTimeBtwShots;
}
void Update ()
{
if(timeBtwShots <= 0)
{
Instantiate(projectile, transform.position, Quaternion.identity);
timeBtwShots = startTimeBtwShots;
} else {
timeBtwShots -= Time.deltaTime;
}
}
}
and the following one for its movement behavior.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovementScript : MonoBehaviour {
public float speed;
public GameObject explosion;
private bool movingleft = true;
//private bool alive = true;
public Transform groundDetection;
void Update () {
transform.Translate(Vector2.left * speed * Time.deltaTime);
RaycastHit2D groundInfo = Physics2D.Raycast(groundDetection.position, Vector2.down, 1f);
if(groundInfo.collider == false)
{
if(movingleft)
{
transform.eulerAngles = new Vector3(0, -180, 0);
movingleft = false;
} else {
transform.eulerAngles = new Vector3(0, 0, 0);
movingleft = true;
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Shot"))
{
Instantiate (explosion, transform.position, Quaternion.identity);
Destroy (gameObject);
GameControl.instance.DogScoredSmall();
}
}
}
As for the projectile itself, it has the following script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyProjectileScript : MonoBehaviour {
public float speed;
private Transform player;
private Vector2 target;
void Start () {
player = GameObject.FindGameObjectWithTag("Player").transform;
target = new Vector2(player.position.x, player.position.y);
}
void Update () {
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
if(transform.position.x == target.x && transform.position.y == target.y){
DestroyProjectile();
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Player")){
DestroyProjectile();
}
}
void DestroyProjectile(){
Destroy(gameObject);
}
}
The Editor does not show any syntax mistakes. All the public variables have their slots filled with the necessary elements in the Object editor. The enemy, however, still does not shoot the projectile. What could be the reason?