Passing parameters in function efficiency?
Hi guys,
Forgive me for a basic question, but i'm not sure on how clean this way of coding is, could you tell me what would be the most efficient way, or if there is no difference?
If I have a large monster class and I am writing an attack that will hit the monsters target and another attack that will hit the monsters target, but also hurt itself, would it be more or less efficient to pass the monster class in the function? it saves me a lot of coding space to have it passed, but if I have 50 similar functions would that not be inefficient?
class MonsterData
{
var name : String;
var gameObject : GameObject;
var target : int;
var curHealth :float;
var maxHealth :float;
var curEnergy :int;
var maxEnergy :int;
var curStrength :float;
var curSpeed :float;
var curDefence :float;
var curAccuracy :float;
var curCritical :float;
var attackSlot1 : AttackData;
var attackSlot2 : AttackData;
var attackSlot3 : AttackData;
var attackSlot4 : AttackData;
var attackSlot5 : AttackData;
// etc etc..
}
//----------------------------------
// ******* VERSION 1:
//----------------------------------
var targetMonster : MonsterData;
var attackingMonster : MonsterData;
function RegularAttack()
{
// camera movement, target monsters, damage calculations...
TakeDamageTarget();
}
function RecoilAttack ()
{
// camera movement, target monsters, damage calculations...
TakeDamageTarget();
TakeDamageSelf();
}
function TakeDamageTarget()
{
targetMonster.gameObject.GetComponent.<Animation>().Play("takeDamage");
SlideHealth(targetMonster);
}
function TakeDamageSelf()
{
attackingMonster.gameObject.GetComponent.<Animation>().Play("takeDamage");
SlideHealth(attackingMonster);
}
// other functions such as PoisonSelf() / PoisonTarget(), FaintSelf / FaintTarget() etc...
//----------------------------------
// ******* VERSION 2:
//----------------------------------
var targetMonster : MonsterData;
var attackingMonster : MonsterData;
function RegularAttack()
{
// camera movement, target monsters, damage calculations...
TakeDamage(targetMonster);
}
function RecoilAttack ()
{
// camera movement, target monsters, damage calculations...
TakeDamage(targetMonster);
TakeDamage(attackingMonster);
}
function TakeDamage(monster : MonsterData)
{
monster.gameObject.GetComponent.<Animation>().Play("takeDamage");
SlideHealth(monster);
}
// other functions such as PoisonSelf() / PoisonTarget(), FaintSelf / FaintTarget() etc...
Answer by ElijahShadbolt · Nov 27, 2016 at 08:16 PM
I would use Version 2, where you pass the specific MonsterData you wish to change, because you'll have to write half as much code for exactly the same effect. Since MonsterData is a Class Type and not a Value Type, the parameter will actually be a reference to the class, not the whole class itself. This should have no impact on performance or efficiency compared to Version 1.
Fantastic, that is just the answer i was looking for. Thank you.
Your answer
