Home > Back-end >  Unity_when I use private void OnCollisionEnter(Collision collision) how to use other's variable
Unity_when I use private void OnCollisionEnter(Collision collision) how to use other's variable

Time:08-30

example monster hit bullet bullet1 have int damage in scripts(name is Bullet1) but bullet is not one other bullet2 have int damage in scripts(name is Bullet2) too

in this situation if monster hit bullet1 > collision.getcomponent().gamage if mosnter hit bullet2 > collision.getcomponent().gamage . . .

this is so dirty

I'm not good at english sorry

CodePudding user response:

Suggestions:

I think I understood what you trying to say hopfully I am not wrong lol :P

Anyways if you don't wanna call and detect if the collided object has etc script all the time so for the best practice right now you can use interfaces so let me show you through code:


public interface IDamageAble {

   public void DoDamage( int health );
}

now just implement that interface into your bullet class like:

public class Bullet : MonoBehavior, IDamageAble {

   public int damage = 5;

   public void DoDamage( int health ) {

      health -= damage;
   }
}

same goes for other bullets with different damage because its public damage so you can have different values for different types of bullets no need to create Bullet_1 or Bullet_2 (unless you want to change every functionality of it) but never the less now you can just check for IDamageAble instead of every bullet like:

public class Monster : MonoBehavior {

    public int monsterHealth;

    private void OnCollisionEnter( Collision other ) {

        var _damageAble = other.getcomponent<IDamageAble>();
        _damageAble?.DoDamage( monsterHealth );   
     }
}

You can enhance its usage to use for any other cases in better way but this was just a simple example hopefully I made sense in it lol anyways.

Hope it works for you... Happy coding :)

CodePudding user response:

You can use Inheritance to get what kind of bullet hit the monster.

Usage:

Bullet.cs

public class Bullet : MonoBehaviour 
{ 
    int damage;

    public int GetDamage() {
        return damage;
    }
}

Bullet1.cs

public class Bullet1 : Bullet 
{
    ... 

    void Start()
    {
       damage = 5;
    }

    ...
}

Bullet2.cs

public class Bullet2 : Bullet 
{
    ... 

    void Start()
    {
       damage = 10;
    }

    ...
}

Monster.cs

public class Monster : MonoBehaviour 
{

    ...
        
    void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision.gameObject.name   " Hit! damage is "   collision.gameObject.GetComponent<Bullet>().GetDamage());
    }


    ...
}
  • Related