One unit hitting another

I’m new to unit and i’m making this hack and slash game.
I’m having trouble with making one unit deal damage to another, though

void OnTriggerEnter2D(Collider2D collider){
if(!collider.gameObject.GetComponent()){
GameObject obj=collider.gameObject;
print(obj);
}
}

void hit(){
print(obj);
if(kicked&&obj){
obj.GetComponent().DealDamage(damage);
print(obj.GetComponent().value);
}
}

the hit() method is being called by the animation (when the kick animation is performed). by the way, when you kick, the bool kicked becomes true. The hit method has been printing (null) every single time.

Your problem in hit() is ‘obj’ That method has no idea what that object is. It seems that you haven’t declared what it is.
In OnTriggerEnter2D you said GameObject obj = collider.gameObject. That’s great, you made a variable to hold obj. The problem is, the ‘GameObject obj’ only exists in the scope of OnTriggerEnter2D(). So in hit(), the scope of ‘GameObject obj’ doesnt exist. The compiler has no reference to obj.

I dont know enough about your code to help all that much but you need to get a reference to the right object that you want for obj inside the hit method. Whether that be creating a global/local variable to store the result or inside hit finding the object. Or passing the object in with hit as a parameter.

i forgot to mention. I actually declared obj before void start()

public GameObject obj;

Perfect :slight_smile:
Then do this:

void OnTriggerEnter2D(Collider2D collider){
   if(!collider.gameObject.GetComponent<floor>()){ 
      // I removed 'GameObject obj', you just need 'obj' so that it uses the 'obj' variable you already created.
      obj=collider.gameObject;
      print(obj);
   }
}