-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathAvatarSpawnerHandlerMotif.cs
90 lines (76 loc) · 2.98 KB
/
AvatarSpawnerHandlerMotif.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (c) Meta Platforms, Inc. and affiliates.
#if FUSION2
using Fusion;
using UnityEngine;
using System.Collections;
using Meta.XR.MultiplayerBlocks.Shared;
using Meta.XR.MultiplayerBlocks.Fusion;
using MRMotifs.SharedActivities.Spawning;
namespace MRMotifs.SharedActivities.Avatars
{
/// <summary>
/// Handles the spawning of avatars in the scene, managing their positions using the spawn manager.
/// Also, responsible for releasing spawn locations when players leave the scene.
/// </summary>
public class AvatarSpawnerHandlerMotif : MonoBehaviour
{
[Tooltip("Reference to the SpawnManagerMotif, which manages the spawn locations and queues.")]
[SerializeField]
private SpawnManagerMotif spawnManagerMotif;
private NetworkRunner m_networkRunner;
private void Awake()
{
FusionBBEvents.OnSceneLoadDone += OnLoaded;
AvatarEntity.OnSpawned += HandleAvatarSpawned;
FusionBBEvents.OnPlayerLeft += FreeSpawnLocation;
}
private void OnDestroy()
{
FusionBBEvents.OnSceneLoadDone -= OnLoaded;
AvatarEntity.OnSpawned -= HandleAvatarSpawned;
FusionBBEvents.OnPlayerLeft -= FreeSpawnLocation;
}
private void OnLoaded(NetworkRunner networkRunner)
{
m_networkRunner = networkRunner;
}
private void HandleAvatarSpawned(AvatarEntity avatarEntity)
{
StartCoroutine(WaitForSpawnedAndEnqueue(avatarEntity));
}
private IEnumerator WaitForSpawnedAndEnqueue(AvatarEntity avatarEntity)
{
// Additional delay required since Avatars v28+ require some additional time to be loaded
// No event to await the full "readiness" of the avatar is available yet
yield return new WaitForSeconds(1.5f);
while (!spawnManagerMotif.HasSpawned)
{
yield return null;
}
var avatarNetworkObj = avatarEntity.gameObject.GetComponent<AvatarBehaviourFusion>();
if (!avatarNetworkObj.HasStateAuthority)
{
yield break;
}
yield return spawnManagerMotif.StartCoroutine(
spawnManagerMotif.EnqueuePlayerForSpawn(m_networkRunner.LocalPlayer, avatarNetworkObj));
}
private void FreeSpawnLocation(NetworkRunner runner, PlayerRef player)
{
for (var i = 0; i < spawnManagerMotif.OccupyingPlayers.Length; i++)
{
if (spawnManagerMotif.OccupyingPlayers.Get(i) != player)
{
continue;
}
spawnManagerMotif.ReleaseLocationRpc(i, player);
var avatarHandler = FindAnyObjectByType<AvatarMovementHandlerMotif>();
if (avatarHandler != null)
{
avatarHandler.RemoveRemoteAvatarByPlayer(player);
}
}
}
}
}
#endif