B
B
Banpsih2020-06-16 18:38:20
Unity
Banpsih, 2020-06-16 18:38:20

Unity(C#) - Why does the bullet destroy the monster?

what is the point: The bullet should not destroy the monster and at the same time should cause damage to the player. if I set the damage method (code below), then the bullet both destroys the monster (which it should not do) and causes damage to the player (which it should). if I remove the damage method, then the monster cannot be destroyed, but the bullet does not cause damage to the player either. how to fix?
Bullet Code:

float speed = 10f;
    Vector3 dir;
    public Vector3 Direction { set { dir = value; } }
    public SpriteRenderer sprite;
    void Start()
    {
        Destroy(gameObject, 1f);
        sprite = GetComponentInChildren<SpriteRenderer>();

    }
    GameObject parent;
    public GameObject Parent { set { parent=value; } }
         
    
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
        sprite.flipX = dir.x < 0;


    }
    private void OnTriggerEnter2D(Collider2D collider)
    {
        Unit unit = collider.GetComponent<Unit>();
        if (unit && unit.gameObject !=parent)
        {
            //unit.Hit();
            Destroy(gameObject);
        }
    }


Monster Code
public float rate = 2f;
    Bullet bullet;
    protected override void Awake()
    {
        bullet = Resources.Load<Bullet>("bb1");

    }
    void Shoot()
    {
        Vector3 position = transform.position; position.y += 0.5f;
        Bullet bull1 = Instantiate(bullet, position, bullet.transform.rotation) as Bullet;
        bull1.Parent = gameObject;
        bull1.Direction = -bull1.transform.right;


    }
    protected override void Start()
    {

        InvokeRepeating("Shoot", rate, rate);
    }
    protected override void OnTriggerEnter2D(Collider2D collider)
    {
        Unit unit = collider.GetComponent<Unit>();
        if (unit && unit is Player)
        {
            if (Mathf.Abs(unit.transform.position.x - transform.position.x) < 0.5f)
            {

                Hit();

            }
            else
            {

                unit.Hit();
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question