我确实有一个Android多人游戏。我有一个脚本,玩家可以在其中发射武器。但是我确实收到了此错误“尝试在未经授权的情况下为对象发送命令。
我看到了以下答案:https://stackoverflow.com/a/42689614,但是我不知道如何在我的代码中实现它。
这是我当前的播放器脚本代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
namespace S3 {
[RequireComponent(typeof(CharacterController))]
public class MPPlayerController : NetworkBehaviour {
//Handling
public float rotationSpeed = 450;
public float walksSpeed = 5;
public float runSpeed = 8;
public AudioClip shootAudio;
//System
private Quaternion targetRotation;
//Components
private CharacterController controller;
public GameObject bulletPrefab;
public Transform bulletSpawn;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (!isLocalPlayer)
{
return;
}
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
if (input != Vector3.zero)
{
targetRotation = Quaternion.LookRotation(input);
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, rotationSpeed * Time.deltaTime);
}
Vector3 motion = input;
motion *= (Mathf.Abs(input.x) == 1 && Mathf.Abs(input.z) == 1) ? 0.7f : 1;
motion *= (Input.GetButton("Run")) ? runSpeed : walksSpeed;
motion += Vector3.up * -8;
controller.Move(motion * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space))
{
CmdFire ();
}
}
[Command]
void CmdFire()
{
//create the bullet from the prefab
GameObject bullet = (GameObject)Instantiate (bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
AudioManager.instance.PlaySound (shootAudio, transform.position);
//add velocity to the bullet
bullet.GetComponent<Rigidbody> ().velocity = bullet.transform.forward * 20.0f;
//spawn the bullet on the clients
NetworkServer.Spawn (bullet);
//destroy the bullet after 2 seconds
Destroy (bullet, 2);
}
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer>().material.color = Color.blue;
}
}
}