![](/img/trans.png)
[英]Real time sync in Unity using Photon Unity Network(multiplayer)
[英]Unity / Photon - Multiplayer
背景:我正在开发一个小型多人游戏,其中多辆车位于一个 GameObject 下(在汽车选择菜单中使用),但在我正在工作的教程的一部分中,提到玩家控件应位于if (view.IsMine) { my control code here} 但我收到以下错误:NullReferenceException: Object reference not set to an instance of an object CarControl.Update () (at Assets/Code/CarControl.cs:30)
我正在使用的脚本是:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class CarControl : MonoBehaviour
{
PhotonView view;
public float MoveSpeed = 50;
public float MaxSpeed = 15;
public float Drag = 0.98f;
public float SteerAngle = 20;
public float Traction = 1;
private Vector3 MoveForce;
void Gravity()
{
Physics.gravity = new Vector3(0, -1.0F, 0);
}
private void Start()
{
view = GetComponent<PhotonView>();
}
void Update()
{
if (view.IsMine)
{
//Moving
MoveForce += transform.forward * MoveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += MoveForce * Time.deltaTime;
//Steering
float steerInput = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up * steerInput * MoveForce.magnitude * SteerAngle * Time.deltaTime);
//Drag and speed limit
MoveForce *= Drag;
MoveForce = Vector3.ClampMagnitude(MoveForce, MaxSpeed);
//Traction
Debug.DrawRay(transform.position, MoveForce.normalized * 3);
Debug.DrawRay(transform.position, transform.forward * 3, Color.blue);
MoveForce = Vector3.Lerp(MoveForce.normalized, transform.forward, Traction * Time.deltaTime) * MoveForce.magnitude;
}
}
}
PhotonView 在更新开始时似乎为空。 由于您是从对GetComponent<PhotonView>
的调用中分配 PhotonView ,因此很明显没有找到该组件。
使用此脚本检查组件是否在对象上,或将调用从GetComponent
更改为GetComponentInParent
(如果对象在父对象上)或GetComponentInChildren
(如果对象在子对象上)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.