- Home /
reusing code for player, enemies and NPC
Hi. I just realized that my player and my enemies do all the same things (let's say run, jump and shoot).
My problem is that as for now I've to code this three actions two times, one for the player and one for the enemies. I would like to keep the run, jump, shoot code the same and change only the input method (in one case keyboard, for the enemies AI, ideally it should be the same code for other player in a multiplayer game). I can't find any design pattern for this, I'm pretty sure that at some point I found a tutorial in the store for achieving this but I can't find it anymore. Does any of you has experience about this?
Answer by ignacevau · Aug 18, 2018 at 10:46 PM
If I understand your question correct, you just want to use the same script for your enemies as for your player. This is fairly easy to do, you could for example check for the object's tag in the script, but performance-wise I would recommend to just use an public enumeration:
public enum Type { Player, Enemy }
public class ObjectJump : MonoBehaviour
{
public Type type;
public float playerJumpHeight;
public float enemyJumpHeight;
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
if(type == Type.Player)
{
Jump(playerJumpHeight);
}
else if(type == Type.Enemy)
{
Jump(enemyJumpHeight);
}
}
}
void Jump(float jumpHeight)
{
//Make the object jump
}
}
Your answer
Follow this Question
Related Questions
Optimising for large groups of enemies 3 Answers
Walk Aroud a Target Randomly 2 Answers
Ai Obstacle Avoidance 1 Answer
Evade a Collider on Vector3.forward 3 Answers