SanAndreasUnity/Assets/Scripts/Behaviours/SpawnManager.cs

89 lines
2.6 KiB
C#
Raw Normal View History

2019-04-24 14:58:13 +00:00
using System.Collections.Generic;
using UnityEngine;
2019-04-24 17:18:18 +00:00
using SanAndreasUnity.Net;
using SanAndreasUnity.Utilities;
using System.Linq;
2019-04-24 14:58:13 +00:00
namespace SanAndreasUnity.Behaviours
{
public class SpawnManager : MonoBehaviour
{
2019-04-24 17:18:18 +00:00
List<Transform> m_spawnPositions = new List<Transform>();
2019-04-24 14:58:13 +00:00
GameObject m_container;
void Start()
{
this.InvokeRepeating(nameof(UpdateSpawnPositions), 1f, 1f);
2019-04-24 17:18:18 +00:00
this.InvokeRepeating(nameof(SpawnPlayers), 1f, 3f);
2019-04-24 14:58:13 +00:00
}
void UpdateSpawnPositions()
{
2019-04-24 17:39:38 +00:00
if (!Loader.HasLoaded)
return;
2019-04-24 17:18:18 +00:00
if (NetStatus.IsServer && Ped.Instance)
2019-04-24 14:58:13 +00:00
{
2019-04-24 17:18:18 +00:00
if (null == m_container)
2019-04-24 14:58:13 +00:00
{
// create parent game object for spawn positions
2019-04-24 17:18:18 +00:00
m_container = new GameObject("Spawn positions");
2019-04-24 14:58:13 +00:00
// create spawn positions
2019-04-24 17:18:18 +00:00
m_spawnPositions.Clear();
for (int i = 0; i < 5; i++)
2019-04-24 14:58:13 +00:00
{
2019-04-24 17:18:18 +00:00
Transform spawnPos = new GameObject("Spawn position " + i).transform;
spawnPos.SetParent(m_container.transform);
m_spawnPositions.Add(spawnPos);
NetManager.AddSpawnPosition(spawnPos);
2019-04-24 14:58:13 +00:00
}
}
// update spawn positions
2019-04-24 17:18:18 +00:00
m_spawnPositions.RemoveDeadObjects();
foreach (Transform spawnPos in m_spawnPositions)
2019-04-24 14:58:13 +00:00
{
2019-04-24 17:18:18 +00:00
spawnPos.position = Ped.Instance.transform.position + Random.insideUnitCircle.ToVector3XZ() * 15f;
2019-04-24 14:58:13 +00:00
}
}
}
2019-04-24 17:18:18 +00:00
void SpawnPlayers()
{
if (!NetStatus.IsServer)
return;
2019-04-24 17:39:38 +00:00
if (!Loader.HasLoaded)
return;
2019-04-24 17:18:18 +00:00
var list = NetManager.SpawnPositions.ToList();
list.RemoveDeadObjects();
if (list.Count < 1)
return;
foreach (var player in Player.AllPlayers)
{
// if player is not spawned, spawn him
2019-04-24 17:39:38 +00:00
if (player.OwnedGameObject != null)
continue;
2019-04-24 17:18:18 +00:00
var spawn = list.RandomElement();
2019-04-24 17:39:38 +00:00
var ped = Ped.SpawnPed(Ped.RandomPedId, spawn.position, spawn.rotation);
player.OwnedGameObject = ped.gameObject;
2019-04-24 17:18:18 +00:00
2019-04-24 17:39:38 +00:00
Debug.LogFormat("Spawned ped for player {0}, net id {1}", player.connectionToClient.address, ped.netId);
2019-04-24 17:18:18 +00:00
}
}
2019-04-24 14:58:13 +00:00
}
}