- Home /
GameObject not getting passed trough
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<Bullet>().enemy = enemy;
Debug.Log(enemy);
newBullet.GetComponent<Bullet>().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<Enemy>().hp -= damage;
Destroy(this.gameObject);
} else if(enemy = null)
{
Destroy(this.gameObject);
}
}
}
The enemy has a Nav Mesh Agent component
Comment
Best Answer
Answer by rocketmanr8711 · Jun 07, 2021 at 01:07 PM
@Bram280 You're big problem is the "else if(enemy = null)" will set enemy to null every time. But also be aware that bullet's Update may be called before the tower has a chance to set enemy.
OMG thank you so much, I totally missed that. Why am I so stupid to do that XD. Really thanks for your help!