Question by
TheDogeQuake · Aug 03, 2020 at 08:22 AM ·
collisiondamage
How do i apply my script to multiple instantiated enemies
Im very new to CSharp so apologies for the basic and poorly written code
using UnityEngine; using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour {
public float moveSpeed = 5f;
public float health = 3f;
public float EnemyDistance = 0.01f;
public Transform Enemy;
private float enemyDamage = 1f;
void TakeDamage(float amount)
{
health -= amount;
if(health <= 0f)
{
Die();
}
}
void Die()
{
Application.LoadLevel(Application.loadedLevel);
}
public Rigidbody2D rb;
Vector2 movement;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
float distanceToPlayer = Vector3.Distance(transform.position, Enemy.position);
if (distanceToPlayer < EnemyDistance)
{
TakeDamage(enemyDamage);
}
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.deltaTime);
}
}
The script works when applied to the player but i want to instantiate multiple enemies using a spawner, I think i have to change the public Transform Enemy in some way but i don't know how to go about applying the ability to damage the player to any enemy that spawns.
Comment