I’m new to Unity here and I just followed a tutorial on launching projectiles in 2D. I created an Arrow Script and its prefab. The bows and arrows work. However, I am unable to buff the Arrow damage as the game object is created when shot. Bow is inside my player, but arrows are created from the bow
This is my code
Arrow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Arrow : MonoBehaviour
{
public int damage = 3;
public float speed = 5f;
public float lifeTime = 1f;
public ArrowData arrowData;
public GameObject destroyEffect;
// Start is called before the first frame update
void Start()
{
// Physics.IgnoreCollision(FindGameObjectWithTag("Player").GetComponent<Collider>(), GetComponent<Collider>());
this.damage = arrowData.damage;
this.speed = arrowData.speed;
this.lifeTime = arrowData.lifeTime;
Invoke("DestroyProjectile", lifeTime);
}
private void Update()
{
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
void DestroyProjectile()
{
Instantiate(destroyEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D collider)
{
if(collider.GetComponent<EnemyHealth>() != null)
{
EnemyHealth health = collider.GetComponent<EnemyHealth>();
health.Damage(damage);
Destroy(gameObject);
}
}
}
Bow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bow : MonoBehaviour
{
public float offset;
public GameObject projectile;
public Transform shotPoint;
private float timeBetweenShots;
public float startTimeBetweenShots;
private void Update() {
//weapon position
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if(timeBetweenShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
timeBetweenShots = startTimeBetweenShots;
}
}
else
{
timeBetweenShots -= Time.deltaTime;
}
}
}
Buff.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Buff : ScriptableObject {
public abstract void Apply(GameObject target);
}
ArrowDamage.cs (the buff)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Buff/BowDamage")]
public class ArrowDamage : Buff
{
public int damage;
ArrowData arrowData;
public override void Apply(GameObject target)
{
arrowData.damage += this.damage;
}
}
Powerup.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Powerup : MonoBehaviour
{
public Buff buff;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("Player"))
{
buff.Apply(collision.gameObject);
Destroy(gameObject);
}
}
}