- Home /
Problem with weapon and projectiles system in dealing damage to enemies?
So i have 2 scripts: one is for weapons and the other is for projectiles. The weapon script will instantiate the gameobject projectiles and the projectiles will move the gameobject foward. I want to have a damage variable for the projectiles when it hits enemies but the damage depends on the weapon not the projectiles. So my first idea is to use a constructor in the projectile script and then parse the damage variable from the weapon script when instantiate the projectile to the constructor. But after research i know that you have to avoid constructor in monobehaviour. So anyone can tell me any ways that don't need constructor.
Here is the weapon script:
// shoot projectile toward the mouse position
void ShootProjectile()
{
if (timeBtwShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectilePrefab, shotPos.position, transform.rotation);
projectile = projectilePrefab.gameObject.GetComponent<Projectile>();
Debug.Log(projectile);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
And here is the projectile scripts:
public float speed;
private Rigidbody2D rb;
private Enemies enemy;
private float damage;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = transform.right * speed;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Enemy")
{
enemy = collision.GetComponent<Enemies>();
enemy.health -= damage;
}
}
Answer by Larry-Dietz · Dec 08, 2019 at 04:05 PM
Make the damage variable in your projectile script public, then after you instantiate your projectile, and assign the projectile script to projectile, just set the damage with projection.damage = DamageAmount;
Hope this helps, -Larry
Your answer
Follow this Question
Related Questions
I cant get my projectiles to do damage or keep them from going through my player 1 Answer
Using the increasing and decreasing value function to deal damage 2 Answers
How do I make a projectile go in a straight line after colliding with another projectile? 0 Answers