Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

Handling Collisions unity

// Step 1: Create interface
public interface IHealth
{
	void TakeDamage(int damage);
}

// Step 2: Implement in Victim
public class Player : IHealth
{
	public void TakeDamage(int damage)
	{
		// handle when take damage
	}
}

// Step 3: Implement in Attacker
public class Bullet
{
	int damage = 100;
	public void OnCollisionEnter(Collision2D col)
	{
	    //check col => implement IHealth or not?
		var hp = col.gameObject.GetComponent<IHealth>();
		if (hp != null)
		{
			hp.TakeDamage(damage);
		}
	}
}
 
PREVIOUS NEXT
Tagged: #Handling #Collisions #unity
ADD COMMENT
Topic
Name
3+8 =