Citizens has an extensive API for working with NPCs. Make sure you always are using an up-to-date build of the CitizensAPI to ensure that your plugin works with the latest release of Citizens.
Javadocs can be found at https://jd.citizensnpcs.co
Linking Properly In Java
Citizens is built using Maven. Your plugin that links to Citizens should be using Maven as well (or Gradle for experts).
For Maven users: your
pom.xml should include this repository:
<repository> <id>everything</id> <url>https://repo.citizensnpcs.co/</url> </repository>
and this dependency:
<dependency> <groupId>net.citizensnpcs</groupId> <artifactId>citizens-main</artifactId> <version>VERSION</version> <type>jar</type> <scope>provided</scope> </dependency>
VERSION with the current version of Citizens (check the filenames at http://ci.citizensnpcs.co/job/Citizens2/ for current version ID), formatted like
2.0.29-SNAPSHOT (but with the version numbers changed to the relevant version). (Note: yes,
SNAPSHOT is a literal word, don't fill it in with anything).
Note that for most purposes, it's best to link
citizens-main rather than the API project, as many useful classes and utilities are not in the API. The main Citizens project includes the API and adds more options.
Hooking Into Citizens
Hooking into Citizens is as simple as creating a basic plugin and adding the line depend: [Citizens] into your plugin.yml. Next, you will need to listen for CitizensEnableEvent before using Citizens. A common basic entry point is the CitizensAPI class. This gives you access to the global NPCRegistry for NPCs, as well as the TraitFactory which allows trait registration. If Citizens is not loaded or you didn't wait for CitizensEnableEvent, all CitizensAPI.* methods will return null.
Creating an NPC
The simplest way to create an NPC is to use an NPCRegistry, which manages the storage and creation of NPCs. The default registry is given by CitizensAPI.getNPCRegistry(), and you can create new ones with different storage methods by calling other CitizensAPI methods. A Player NPC with name "fullwall" could then be created like this:
NPC npc = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, "fullwall");
Checking if an entity is a Citizens NPC
Citizens NPCs will have the "NPC" Entity metadata set to true.
boolean isCitizensNPC = entity.hasMetadata("NPC"); This method doesn't even require a dependency on Citizens, as it works entirely through Spigot!
Making an NPC Move
Want to make an NPC pathfind to a location?
Creating a Trait
Traits are persistent, attachable objects that are linked to an NPC and provide specific functionality. This can be anything from custom AI to a simple talking trait.
To register a trait, we use the TraitFactory class. This controls registration for your custom traits.
Dos and Don'ts
- Use Spigot Entity API with npc.getEntity()
- Create a separate event Listener class if you expect there to be many trait instances. This may help performance with frequently called events.
- Honor npc.isProtected() If this is true the NPC should be 'invulnerable' to normal damaging effects.
- Use CitizensAPI.getNPCRegistry().isNPC() to check if an entity is a NPC. Real players and player-type NPCs will both return true for instanceof Player.
- Attempt to access npc.getEntity() from within traits until onSpawn() has been called or npc.isSpawned() returns true.
- Change anything in npc.getNavigator().getDefaultParams() unless you're sure you want a global change. Use the localParams() instead after setting a navigation target.
- Assume a NPC is a Player. Mob types have some important differences.
Citizens comes by default with Traits for its built-in commands. You can see these Traits in the JavaDocs http://jd.citizensnpcs.co/net/citizensnpcs/api/trait/trait/package-frame.html and also in the Citizens2 GitHub https://github.com/CitizensDev/Citizens2/tree/master/main/src/main/java/net/citizensnpcs/trait.
For example, you might add a piece of armor to an NPC using
npc.getOrAddTrait(Equipment.class).set(EquipmentSlot.BOOTS, new ItemStack(Material.LEATHER_BOOTS, 1));
Citizens implements its own Listeners and will call new NPC-specific versions of many common events. This saves Trait developers the trouble of finding their npcs from the normal event entities. The event object these events provide are just like their Spigot counterparts with the addition of the getNPC() method.
See the [Javadocs] for a full list.
Using the AI API
The AI API of Citizens can be broken down into two parts - GoalController and Navigator.
A Goal is a repeatable, abstract unit of work that can be performed by an NPC. For example, moving to a different location or attacking an enemy until it dies. It can be registered with a GoalController with a priority (higher is more important). The highest priority goal which can be executed will be prioritised. NPC contains getDefaultGoalController() for this purpose.
The GoalSelector allows a great deal of flexibility within goal implementations. It allows firstly the dynamic selection of sub-goals and the concurrent execution of many sub-goals, and can stop execution at any time.
Modern plugins should use the Behavior interface which allows a behavior tree-based AI approach that is backwards compatible with Goals and GoalControllers. More info about Behavior is available here: https://jd.citizensnpcs.co/net/citizensnpcs/api/ai/tree/Behavior.html
You can easily create trees of behaviors such as in the following example:
The second concept is the Navigator. This controls the pathfinding aspects of the NPC. The Navigator can have one target at a time, and will call events to notify of completion/cancellation:
You can use the NavigatorParameters class to control various aspects of pathfinding. The default parameters are copied to create the "local" parameters whenever a new path is started - modify local parameters after setting your path target! The pathfinding range of the Navigator is the maximum range it will search when attempting to find a path to the target. This is usually set by the server admin. The speed modifier of the Navigator is the % modified movement speed of the NPC while moving to the target.
Using the Persistence API
Sometimes, traits can store a lot of simple variables such as primitives, Strings, Locations, and others. Saving/loading them via the trait API can be a little bit of overkill.
Citizens provides a simple Persistence API to automatically save and load these variables using DataKeys. The key to this API is the @Persist annotation. Sample code is provided below.
More advanced use of the API can be found in the @DelegatePersistence annotation. This allows complex types such as Locations to be saved and loaded with finer grained control. These types can be given default delegates by calling PersistenceLoader#registerPersistDelegate(Persister) - Location has a built in Persister for convenience.