I have a GameObject Tower which needs to find all enemies in its area and fire bullets at it but the enemy gameObject is not passed trough in the bullet script somehow.
Tower script:
private void Shoot(GameObject enemy)
{
GameObject newBullet = Instantiate(bullet, transform.position, Quaternion.identity);
newBullet.GetComponent().enemy = enemy;
Debug.Log(enemy);
newBullet.GetComponent().damage = damage;
}
Debug.Log(enemy) displays the enemy correctly.
Bullet script:
public class Bullet : MonoBehaviour
{
public GameObject enemy;
[SerializeField] float movementSpeed = 2f;
public int damage = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, enemy.transform.position, 0.5f * Time.deltaTime * movementSpeed);
if((Vector3.Distance(transform.position, enemy.transform.position) <= 0.1f))
{
enemy.GetComponent().hp -= damage;
Destroy(this.gameObject);
} else if(enemy = null)
{
Destroy(this.gameObject);
}
}
}
The enemy has a Nav Mesh Agent component
↧