using FishNet.Object; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Serialization; namespace Agame { /// /// 按攻击键在当前位置生成一个方块,生成动作经 ServerRpc 在服务端执行。 /// /// 输入来自 Player 根节点上 PlayerInput 的 Attack 动作 —— 与 /// 共用同一个 PlayerInput(因此 PlayerInput 的启用/禁用也统一由 PlayerController 按所有权管理, /// 这里只读动作,不再自己 enable 组件)。 /// public class PlayerCubeCreator : NetworkBehaviour { [Tooltip("要生成的方块预制体。必须已登记进 FishNet 的可生成预制体列表(DefaultPrefabObjects)。")] [FormerlySerializedAs("CubePrefab")] [SerializeField] private NetworkObject cubePrefab; private InputAction _attackAction; private void Awake() { // Awake 中不得访问 IsOwner,这里只做纯本地缓存。 _attackAction = PlayerInputNames.Resolve(GetComponent(), PlayerInputNames.Attack, this); } private void Update() { // 只让拥有者发起攻击,否则每个客户端都会去指挥别人的玩家造方块。 if (!IsOwner) return; if (_attackAction != null && _attackAction.WasPressedThisFrame()) SpawnCube(); } [ServerRpc] private void SpawnCube() { if (cubePrefab == null) { Debug.LogError( $"[{nameof(PlayerCubeCreator)}] {name} 的 Cube Prefab 没有指定,无法生成方块。", this); return; } NetworkObject obj = Instantiate(cubePrefab, transform.position, Quaternion.identity); Spawn(obj); // NetworkBehaviour 对 ServerManager.Spawn 的快捷封装 } } }