Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active September 30, 2021 19:50
Show Gist options
  • Save charlieamat/afa8cd995cc8acb0e2a9fd03713f3264 to your computer and use it in GitHub Desktop.
Save charlieamat/afa8cd995cc8acb0e2a9fd03713f3264 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — Script Interactions
  • Create MeleeWeapon.cs
    • A melee weapon is a great example for OnTriggerEnter() because it needs to know when it comes in contact with a combatant
  • Add a private, serialized float field called "damage"
  • Implement OnTriggerEnter()
  • Add an if-statement for other.TryGetComponent(out Combatant combatant))
  • Add a call to combatant.Damage(damage) to the body of the if-statement
    • This behavior depends on Unity's physics system
    • We'll need to add a collider to both the melee weapon and combatant GameObjects
  • Switch to Unity
  • Set up the scene and verify the behavior
public class Combatant : MonoBehaviour
{
public float Health;
public void Damage(int damage)
{
Health = Math.Max(0, Health - damage);
}
}
public class MeleeWeapon : MonoBehaviour
{
[SerializeField] private float damage;
public void OnTriggerEnter(Collider other)
{
if (other.TryGetComponent(out Combatant combatant))
{
combatant.Damage(damage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment