如何在Unity中实时显示玩家的摄像头?(我尝试用光子)



我正在尝试制作一款多人游戏,其中每个玩家都有他们的网络摄像头显示在他们的化身面前。我正在获得空引用异常:对象引用未设置为对象的实例。下面的代码附加到一个四元组,其中网络摄像头的输出是应该显示为jpeg格式。如有任何帮助,不胜感激。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class photonwebcam : MonoBehaviour
{  
WebCamTexture webcamTexture;
PhotonView photonView;
void Start()
{    
PhotonView photonView = PhotonView.Get(this);
if (!webcamTexture.isPlaying)
{
webcamTexture = new WebCamTexture();
Renderer renderer = GetComponent<Renderer>();
renderer.material.mainTexture = webcamTexture;
webcamTexture.Play();
}

}
void FixedUpdate()
{   

Texture2D tex = new Texture2D(webcamTexture.width, webcamTexture.height, TextureFormat.RGB24, false);
tex.SetPixels(webcamTexture.GetPixels());
tex.Apply();
byte[] bytes = tex.EncodeToJPG();
photonView.RPC("VideoToBytes", RpcTarget.AllBuffered, bytes);
Resources.UnloadUnusedAssets();

}
[PunRPC]
public void VideoToBytes(byte[] bytes)
{   
if (bytes!= null)
{
Texture2D texa = new Texture2D(2, 2);
// Load data into the texture.
texa.LoadImage(bytes);
// Assign texture to renderer's material.
GetComponent<Renderer>().material.mainTexture = texa;
}

}
}

一个会给你NullPointerException的问题是,在开始你创建一个本地变量photonView,而不是分配字段。
这种方法的问题是RPC没有针对大数据进行优化,因此图像会延迟。
我认为你可以使用Agora而不是RPC来处理网络摄像头共享。

最新更新