Skip to content
RustPluginGenerator

OnTurretTarget

OnTurretTarget is called when an AutoTurret runs SetTarget, before it accepts the new target and starts tracking it.

Signature
object OnTurretTarget(AutoTurret autoTurret, BaseCombatEntity targ)

Parameters

Hook parameters
ParameterTypeDescription
autoTurretAutoTurretThe AutoTurret that is about to acquire a target. Use it to read the turret's owner, position, auth list or mode.
targBaseCombatEntityThe BaseCombatEntity the turret is trying to lock onto. It can be a player or any combat entity and may be null when the turret is clearing its target.

Return value

Returning any non-null value cancels the original SetTarget body, so the turret keeps its previous target and never accepts targ (or never clears it if targ was null). Returning null lets the vanilla assignment proceed unchanged. The returned object itself is not used by the game.

How it works

The hook fires inside AutoTurret.SetTarget, the single place where a turret commits to (or clears) a target. This is reached when the turret's scanning logic picks a candidate BaseCombatEntity, when it loses a target, and when its internal update loop re-evaluates what it should be aiming at. autoTurret is the turret instance, so you can inspect OwnerID, net.ID.Value, position or the authorization list via GetBuildingPrivilege() on the surrounding block. targ is the candidate being set; it may be null when the turret is being told to drop its current target, so always null-check before reading IsNpc, ToPlayer() or health. Declaring targ as BasePlayer narrows the hook so Oxide only calls it for player candidates; declaring it as BaseCombatEntity (the default) catches NPCs, animals and players. Because it runs on turret scan ticks, keep the body cheap: no Puts/PrintWarning, no heavy entity queries.

Example plugin: Prevent turrets from locking onto players wearing a peacekeeper

TurretPeacekeeper.cs
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("TurretPeacekeeper", "RustPluginGenerator", "1.0.0")]
    [Description("Prevents defence turrets from targeting players who hold the peacekeeper permission")]
    public class TurretPeacekeeper : RustPlugin
    {
        private const string PermExempt = "turretpeacekeeper.exempt";

        private PluginConfig config;

        private class PluginConfig
        {
            [JsonProperty("Only affect unowned (defence) turrets")]
            public bool DefenceTurretsOnly = true;

            [JsonProperty("Show a chat notice when a turret spares a player")]
            public bool NotifyPlayer = false;
        }

        protected override void LoadDefaultConfig() => config = new PluginConfig();

        protected override void LoadConfig()
        {
            base.LoadConfig();
            try
            {
                config = Config.ReadObject<PluginConfig>();
                if (config == null) throw new Exception();
            }
            catch
            {
                PrintWarning("Configuration file is invalid, using defaults");
                LoadDefaultConfig();
            }
            SaveConfig();
        }

        protected override void SaveConfig() => Config.WriteObject(config);

        protected override void LoadDefaultMessages()
        {
            lang.RegisterMessages(new Dictionary<string, string>
            {
                ["Spared"] = "A turret spared you because you are marked as a non-combatant."
            }, this);
        }

        private string Msg(string key, string userId = null, params object[] args) => string.Format(lang.GetMessage(key, this, userId), args);

        private void Init()
        {
            permission.RegisterPermission(PermExempt, this);
        }

        private object OnTurretTarget(AutoTurret autoTurret, BaseCombatEntity targ)
        {
            if (autoTurret == null || targ == null) return null;

            var player = targ as BasePlayer;
            if (player == null || player.IsNpc) return null;

            if (config.DefenceTurretsOnly && autoTurret.OwnerID != 0) return null;

            if (!permission.UserHasPermission(player.UserIDString, PermExempt)) return null;

            if (config.NotifyPlayer && player.IsConnected)
            {
                player.ChatMessage(Msg("Spared", player.UserIDString));
            }

            return true;
        }
    }
}

The plugin lets server owners make turrets ignore players who are not eligible for PvP, for example players with a specific permission or a worn marker item. When OnTurretTarget fires, it checks the candidate: if it is not a player it returns null immediately so NPC handling is untouched. For players it verifies the turret acts as a defence turret (no owner, i.e. outpost/monument style) and whether the player holds the configured exemption permission. When the player is exempt, the hook returns true, which blocks the original SetTarget and the turret never locks on. Because the hook fires on every scan, the code only does a permission lookup and returns; no chat output or logging happens inside it. The permission name is registered in Init and the exemption flag is read from config.

Common use cases

  • Peacekeeper zones for outpost turrets

    Return non-null for players that should not be shot by NPC defence turrets, leaving owned player turrets unaffected by checking OwnerID.

  • Whitelist turret targets by team

    Block targeting of players on a VIP team by resolving currentTeam with RelationshipManager and returning true when they are on the protected team.

  • Log or record targeting without changing gameplay

    Return null while incrementing a lightweight in-memory counter so admins can review which players a turret locked onto, without altering SetTarget.

Pitfalls

  • targ can be null

    SetTarget is also used to clear a turret's target, so guard against null before calling ToPlayer() or reading Health().

  • Return true blocks clearing too

    Returning non-null when targ is null prevents the turret from dropping its old target, which can leave it stuck aiming at a dead or gone entity.

  • This is a hot path

    SetTarget runs during each turret scan; avoid PrintWarning, Puts, LINQ on large collections or data file writes inside the hook.

Plugin recipes that use OnTurretTarget

Build a plugin with OnTurretTarget

Describe what should happen and get a compiled plugin that uses this hook.

Prompt: Peacekeeper zones for outpost turrets using the OnTurretTarget hook, with a config file and a permission
Generate this plugin

Edit the prompt on the next screen. 2 free plugins a month, no card.

Last updated Oct 26, 2026. Found a mistake? Email support@rustplugingenerator.com.

Build a plugin with OnTurretTarget

Generate