XRGrabInteractable and Photon Pun Unity VR - unity3d

I had a script that would debug "Wow I shot" whenever the player presses the trigger, this is what it looked like:
XRGrabInteractable grabbable;
// Start is called before the first frame update
void Start()
{
grabbable = GetComponent<XRGrabInteractable>();
grabbable.activated.AddListener(FireBullet);
}
public void FireBullet(ActivateEventArgs arg)
{
Debug.Log("Wow I shot");
}
that works fine, but then I tried to add Multiplayer/Photon networking and I changed it to this:
XRGrabInteractable grabbable;
// Start is called before the first frame update
void Start()
{
grabbable = GetComponent<XRGrabInteractable>();
grabbable.activated.AddListener(FireBulletToServer);
}
void FireBulletToServer(ActivateEventArgs arg)
{
photonView.RPC("FireBullet", RpcTarget.All);
}
[PunRPC]
public void FireBullet(ActivateEventArgs arg)
{
Debug.Log("Wow I shot");
}
``` now it doesnt run anymore at all, any ideas?
Nothing yet really :shrug:

Related

Cursor not visible first time escape is pressed but all subsequent times it is

I am new to learning C# so I'm trying to figure out little bits at a time. Today's task is to have my cursor appear and disappear as I open a panel. I know that unity is weird and you have to build your project to see the cursor changes. However, on said build, when I press escape my panel appears but my cursor doesn't. If I close and reopen the panel the cursor will show up and then everything works as it should.
Something in my code that is causing this or is it just a unity bug?
Also, since I am new to this, any advice is appreciated. Thank you for your time!
public class MenuManager : MonoBehaviour
{
public GameObject pauseMenu;
public bool gamePause = false;
bool cursorHide = true;
// Start is called before the first frame update
void Start()
{
UpdateCursor();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
cursorHide = !cursorHide;
UpdateCursor();
PauseMenuOpen();
}
}
private void PauseMenuOpen()
{
if (!gamePause)
{
pauseMenu.SetActive(true);
gamePause = true;
}
else
{
pauseMenu.SetActive(false);
gamePause = false;
}
}
private void UpdateCursor()
{
Cursor.visible = !cursorHide;
}
public void QuitGame()
{
Application.Quit();
}
}
Use this code. it'll work
private bool isCursorHide;
private void Update(){
if (Input.GetKeyDown(KeyCode.Escape))
CursorToggler();
}
private void CursorToggler(){
if(isCursorHide){
isCursorHide =!isCursorHide;
Cursor.visible = isCursorHide;
}
else{
isCursorHide =!isCursorHide;
Cursor.visible = isCursorHide;
}
}

How to network a VR button with PUN in Unity?

I've been working on a solution for weeks now and I think it's time to reach out. I'm trying to make a button that plays a sound when pressed by a controller, everyone will hear that sound. Using VRTK and PlayoVR, I'm able to make a non-networked version where the player can put their hand through a cube, click the trigger from the controller, and it makes a sound.
This is the code for that cube:
namespace VRTK.Examples {
using UnityEngine;
public class Whirlygig : VRTK_InteractableObject
{
public GameObject AudioSource;
public AudioSource LeftSpeaker;
public override void StartUsing(VRTK_InteractUse currentUsingObject =
null)
{
AudioSource.GetComponent<AudioSource>().Play();
}
}
}
Where I get lost is how to network it with Photon Unity Networking. This is what I have:
namespace PlayoVR
{
using UnityEngine;
using VRTK;
using UnityEngine.Video;
using NetBase;
public class PlaySync : Photon.MonoBehaviour
{
public AudioSource LeftSpeaker;
public GameObject Whirlgig;
private bool StartUsing;
// Use this for initialization
void Awake()
{
GetComponent<VRTK_InteractableObject>().InteractableObjectUsed +=
new InteractableObjectEventHandler(DoPlay);
}
void DoPlay(object sender, InteractableObjectEventArgs e)
{
StartUsing = true;
}
// Update is called once per frame
void Update()
{
// Handle firing
if (StartUsing)
{
CmdPlay();
StartUsing = false;
}
}
void CmdPlay()
{
photonView.RPC("NetPlay", PhotonTargets.All);
}
[PunRPC]
void NetPlay()
{
LeftSpeaker.Play();
}
}
}
As you can probably see, I'm a beginner. With this code, when I put my hand in the cube and press the trigger, nothing happens. If anyone can provide any help or even an alternative, I'd be very grateful.
Kind regards,
TheMusiken

Why delegate event show NullReferenceException?

I follow the tutorial write the code ,but still show this error,the script already attach to the game object
This issue caused by the Execution Order of Event Functions.
When I checked logs, OnEnable of GameUI was called before Awake of GameController.
So, GameController.instance is null when you access GameController.instance.OnGameInfoChanged in void OnEnable() in GameUI.cs.
In Unity Manual for Execution Order of Event Functions, it says Awake is before OnEnable, I guess it doesn't guarantee always.
So, I think you'd better to modify GameUI.cs like below.
public class GameUI : MonoBehaviour
{
public Text timeLabel;
private bool isInitialized = false;
void Start()
{
isInitialized = true;
GameController.instance.OnGameInfoChanged += this.OnGameInfoChanged;
}
void OnEnable()
{
if (isInitialized)
GameController.instance.OnGameInfoChanged += this.OnGameInfoChanged;
}
void OnDisable()
{
GameController.instance.OnGameInfoChanged -= this.OnGameInfoChanged;
}
void OnGameInfoChanged(GameType type)
{
//...
}
}

Multiplayer [SyncEvent] problem with non-player objects

I'm developing a multiplayer game based on turns.
So I have an script named gameController which is the one who has the global timer to alter the turns and also choose which players are attacking and which players are defending in the current turn.
This script is a singleton attached to a gameObject with a network identity on it (This network identity has no checkboxes marked to be controller by the server). I tried to have this game object spawned to all the clients when the server connects and also to have the game object already in the scene (booth cases aren't working).
Well, the main problem is that in the gameController script I have a checker in the update function to check if any new player is connected. In case is connected, it should call a syncEvent named EventOnNewPlayerAddedDelegate (I tried to call it directly, also using [command] and using [ ClientRpc]) to let the players know that they have to call their function named "OnRegisterPlayer", which is a function in their own player script that calls a function on gameController script, passing the player object (I tried via command and rpc also), something like this: GameController.instance.RegisterPlayer(this);
So anyone knows how can I trigger this SyncEvent to register the player to a non-player object controlled by the server?
Thank you very much.
I attach here a brief of booth scripts to make it easier to understand:
GameController:
public class GameController : NetworkBehaviour
{
public delegate void OnNewPlayerAddedDelegate();
[SyncEvent]
public event OnNewPlayerAddedDelegate EventOnNewPlayerAddedDelegate;
List<GamePlayerManager> players = new List<GamePlayerManager>();
public static GameController instance { get; private set; }
float timePerTorn = 30f;
bool isCountdown = false;
[System.NonSerialized]
public float countdownTime;
int roundNumber = 0;
int NumberOfPlayers;
int NumberOfPlayersChanged;
void Awake()
{
Debug.Log("Awaking ");
if (instance != null)
{
Debug.Log("Destoring ");
DestroyImmediate(this);
return;
}
instance = this;
}
// Use this for initialization
void Start()
{
if (!isServer)
{
return;
}
players = new List<GamePlayerManager>();
StartCountdown(5f);//20
}
void Update()
{
if (isServer)
{
if (isCountdown)
{
countdownTime -= Time.deltaTime;
if (countdownTime <= 0)
{
AlterGlobalTurns();
}
}
}
NumberOfPlayers = NetworkManager.singleton.numPlayers;
if (NumberOfPlayersChanged != NumberOfPlayers)
{
Debug.Log("num of players changed ---> " + NumberOfPlayers);
NumberOfPlayersChanged = NumberOfPlayers;
EventOnNewPlayerAddedDelegate();
//RpcNewPlayerAdded();
//CmdNewPlayerAdded();
}
}
[ClientRpc]
void RpcNewPlayerAdded()
{
Debug.Log("---------------- RpcNewPlayerAdded ------------");
EventOnNewPlayerAddedDelegate();
}
[Command]
void CmdNewPlayerAdded()
{
Debug.Log("---------------- CmdNewPlayerAdded ------------");
EventOnNewPlayerAddedDelegate();
}
public void RegisterPlayer(GamePlayerManager player)
{
Debug.Log("player ---> " + player.name);
if (players.Contains(player))
{
return;
}
Debug.Log("players ---> " + players);
players.Add(player);
}
}
PlayerScript:
public class GamePlayerManager : NetworkBehaviour
{
[System.NonSerialized]
public bool isPlayingOnTorn = true;
void Awake()
{
GameController.instance.EventOnNewPlayerAddedDelegate += OnRegisterPlayer;
}
private void Start()
{
if (!isLocalPlayer)
{
return;
}
}
public override void OnStartServer()
{
GameObject gc = (GameObject)Instantiate(NetworkManager.singleton.spawnPrefabs[2], transform.position, transform.rotation);
NetworkServer.Spawn(gc);
}
void OnRegisterPlayer(){
if (isLocalPlayer)
{
//GameController.instance.RegisterPlayer(this);
//RpcRegisterPlayer();
CmdRegisterPlayer();
}
}
[Command]
void CmdRegisterPlayer(){
Debug.Log("-------------Command Register player -------------");
GameController.instance.RegisterPlayer(this);
}
[ClientRpc]
void RpcRegisterPlayer()
{
Debug.Log("------------- RPC REgister Player -------------");
GameController.instance.RegisterPlayer(this);
}
}
I think I already saw the problem here.
The problem is that GameController is spawned by the playerScript(just if the player is also the host) in the function OnStartServer(). So the first problem is that the GameController doesn't detect the host player because it is not a new connections. And the second problem is when a second client is connected, the GameController detect the client connection and send the event signal faster than the client wakeup, so when the client is already working the signal is gone.
I solved the problem deleting this signal and checking directly in the playerScript if the GameController exists then check if the player is already registered.
My question now is that if there is anyway to instance and awake the server objects before the player(Host), which I understand that the answer is "no" because as the player is the host it needs to be running to have the server.
And the second question is if there is anyway or any signal to know that a new player is connected, and wait until it is awaked.
Thank you very much.
You can check the hole thread at Unity forums: https://forum.unity.com/threads/multiplayer-syncevent-problem-with-non-player-objects.589309/

VRTK_ControllerEvents returning null

I am trying to make a gun in Unity with SteamVR and VRTK but I can't figure out how to properly get controller input. When I use the SteamVR Tracked Controller script I get an IsMatrixValid error and it messes up my HMD. I am currently trying to use VRTK controller events method but it keeps returning as a null even though I followed the video correctly.
Screenshot of script location in project
Video in question: https://www.youtube.com/watch?v=escwjnHFce0
(14:17)
Script in question:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EZEffects;
using VRTK;
public class GunBehavior : MonoBehaviour {
public VRTK_ControllerEvents controllerEvents;
private SteamVR_TrackedObject trackedObj;
public EffectTracer TracerEffect;
public Transform muzzleTransform;
// Use this for initialization
void Start () {
Debug.Log(controllerEvents);
if (controllerEvents)
{
Debug.Log("Hue22");
}
else
{
Debug.Log("work");
}
}
// Update is called once per frame
void Update () {
if (controllerEvents.triggerPressed)
{
ShootWeapon();
}
}
void TriggerPressed(object sender, VRTK.ControllerInteractionEventArgs e)
{
ShootWeapon();
}
void ShootWeapon()
{
RaycastHit hit = new RaycastHit();
Ray ray = new Ray(muzzleTransform.position, muzzleTransform.forward);
TracerEffect.ShowTracerEffect(muzzleTransform.position, muzzleTransform.forward, 250f);
if (Physics.Raycast(ray, out hit, 5000f))
{
Debug.Log("Hueheuhue");
}
}
}
Delete these 3 lines of code from your scrip and it should work
void TriggerPressed(object sender, VRTK.ControllerInteractionEventArgs e)
{
ShootWeapon();
}