Created
November 9, 2013 21:09
-
-
Save bcatcho/7390067 to your computer and use it in GitHub Desktop.
This is a response to a r/Unity3d post that talked about many issues. The main issue I saw was how to separate responsibilities in your components. The example below is not *exactly* what I would do but it get's the point across.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AttackAbility : MonoBehaviour | |
{ | |
// this is how you declare a delgate (in case you didn't know) | |
public delegate void OnDidAttackDelegate(GameObject target, AttackAbility attackAbility); | |
// this the event that other scripts will subscribe on to know when we have attacked | |
public event OnDidAttackDelegate OnDidAttack; | |
private void Update() | |
{ | |
var target = GetTargetGameObject(); // Pretend this function gets you your target | |
if (ShouldAttack(target)) // pretend this function says it's ok to attack | |
{ | |
Attack(target); | |
} | |
} | |
private void Attack(GameObject target) | |
{ | |
DealDamageToTarget(target) // pretend this function deals the damage | |
// !IMPORTANT PART: Tell any subscribers that we just attacked | |
if (OnDidAttack != null) // make sure someone has subscribed to the event | |
{ | |
OnDidAttack(target, this); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GoldStealAbility : MonoBehaviour | |
{ | |
private AttackAbility _cachedAttackAbility; | |
// we need to find the attack ability when we start up | |
public void Start() | |
{ | |
// get the attack ability on this gameObject | |
_cachedAttackAbility = gameObject.GetComponent<AttackAbility>(); | |
if (_cachedAttackAbility != null) | |
{ | |
// subscribe to the attack event | |
_cachedAttackAbility.OnDidAttack += HandleOnDidAttack; | |
} | |
} | |
// this is the method that is triggered on attack | |
public void HandleOnDidAttack(GameObject target, AttackAbility attackAbility) | |
{ | |
StealMoney(target); | |
} | |
public void StealMoney(GameObject victim) | |
{ | |
// Put your steal money code here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment