Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CLYS-116 - Unity example patches #200

Open
wants to merge 2 commits into
base: 0.15
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified Assets/Colyseus/Runtime/Example~/Scenes/LobbyScene.unity
Binary file not shown.
36 changes: 20 additions & 16 deletions Assets/Colyseus/Runtime/Example~/Scripts/ExampleRoomController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using GameDevWare.Serialization;
using LucidSightTools;
using NativeWebSocket;
using Settings;
using UnityEngine;

/// <summary>
Expand Down Expand Up @@ -136,6 +137,11 @@ public class ExampleRoomController
/// </summary>
public List<IColyseusRoom> rooms = new List<IColyseusRoom>();

private Action DisposeNetworkEntitiesOnAdd;
private Action DisposeNetworkEntitiesOnRemove;
private Action DisposeNetworkedUsersOnAdd;
private Action DisposeNetworkedUsersOnRemove;

/// <summary>
/// Returns the synchronized time from the server in milliseconds.
/// </summary>
Expand Down Expand Up @@ -295,7 +301,7 @@ public async Task CreateSpecificRoom(ColyseusClient client, string roomName, str
}

onComplete?.Invoke(true);
LSLog.LogImportant($"Created Room: {_room.Id}");
LSLog.LogImportant($"Created Room: {_room.RoomId}");
_lastRoomId = roomId;
RegisterRoomHandlers();
}
Expand Down Expand Up @@ -326,8 +332,8 @@ public async Task JoinOrCreateRoom(Action<bool> onComplete = null)
}

onComplete?.Invoke(true);
LSLog.LogImportant($"Joined / Created Room: {_room.Id}");
_lastRoomId = _room.Id;
LSLog.LogImportant($"Joined / Created Room: {_room.RoomId}");
_lastRoomId = _room.RoomId;
RegisterRoomHandlers();
}

Expand Down Expand Up @@ -396,14 +402,12 @@ public virtual void RegisterRoomHandlers()
//_room.OnMessage<YOUR_CUSTOM_MESSAGE>("messageNameInCustomLogic", objectOfTypeYOUR_CUSTOM_MESSAGE => { });

//========================
_room.State.networkedEntities.OnAdd += OnEntityAdd;
_room.State.networkedEntities.OnRemove += OnEntityRemoved;

_room.State.networkedUsers.OnAdd += OnUserAdd;
_room.State.networkedUsers.OnRemove += OnUserRemove;
this.DisposeNetworkEntitiesOnAdd = _room.State.networkedEntities.OnAdd(OnEntityAdd);
this.DisposeNetworkEntitiesOnRemove = _room.State.networkedEntities.OnRemove(OnEntityRemoved);

_room.State.TriggerAll();
//========================
this.DisposeNetworkedUsersOnAdd = _room.State.networkedUsers.OnAdd(OnUserAdd);
this.DisposeNetworkedUsersOnRemove = _room.State.networkedUsers.OnRemove(OnUserRemove);


_room.colyseusConnection.OnError += Room_OnError;
_room.colyseusConnection.OnClose += Room_OnClose;
Expand Down Expand Up @@ -439,10 +443,10 @@ private void ClearRoomHandlers()
return;
}

_room.State.networkedEntities.OnAdd -= OnEntityAdd;
_room.State.networkedEntities.OnRemove -= OnEntityRemoved;
_room.State.networkedUsers.OnAdd -= OnUserAdd;
_room.State.networkedUsers.OnRemove -= OnUserRemove;
this.DisposeNetworkEntitiesOnAdd();
this.DisposeNetworkEntitiesOnRemove();
this.DisposeNetworkedUsersOnAdd();
this.DisposeNetworkedUsersOnRemove();

_room.colyseusConnection.OnError -= Room_OnError;
_room.colyseusConnection.OnClose -= Room_OnClose;
Expand Down Expand Up @@ -564,7 +568,7 @@ private void OnUserAdd(string key, ExampleNetworkedUser user)
_users.Add(key, user);

// On entity update...
user.OnChange += changes =>
user.OnChange(() =>
{
user.updateHash = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();

Expand All @@ -574,7 +578,7 @@ private void OnUserAdd(string key, ExampleNetworkedUser user)
{
OnCurrentUserStateChanged?.Invoke(user.attributes);
}
};
});
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public string ServerURL
{
return serverURLInput.text;
}

return ExampleManager.Instance.ColyseusServerAddress;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System;
using System.Collections;
using System.Collections.Generic;
using Colyseus;
using LucidSightTools;
using Settings;
using UnityEngine;
using UnityEngine.SceneManagement;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ public void InitiView(ExampleNetworkedEntity entity)
{
state = entity;
IsMine = ExampleManager.Instance.CurrentUser != null && string.Equals(ExampleManager.Instance.CurrentUser.sessionId, state.ownerId);
state.attributes.OnChange += Attributes_OnChange;
state.OnChange += Entity_State_OnChange;
state.attributes.OnChange(Attributes_OnChange);
state.OnChange(Entity_State_OnChange);

OwnerId = state.ownerId;
Id = state.id;
Expand Down Expand Up @@ -168,7 +168,7 @@ public virtual void OnEntityRemoved()
// Entity removed from room state;
}

virtual protected void Entity_State_OnChange(List<Colyseus.Schema.DataChange> changes)
virtual protected void Entity_State_OnChange()
{
// Only record state change has been updated locally
lastStateTimestamp = state.timestamp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ MonoBehaviour:
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: abda5a440b0b5634b8654ff3a0129b80, type: 3}
m_Script: {fileID: 11500000, guid: 6ed729989615d4b4db072e1e8c41076c, type: 3}
m_Name: ColyseusSettings
m_EditorClassIdentifier:
colyseusServerAddress: localhost
Expand All @@ -19,4 +19,4 @@ MonoBehaviour:
- name: Content-Type
value: application/json
- name: Accept
value: application/json
value: application/json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions Assets/Colyseus/Runtime/Scripts/Managers/ColyseusManager.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
using System.Collections.Generic;
using LucidSightTools;
using Settings;
using UnityEngine;
// ReSharper disable InconsistentNaming

namespace Colyseus
{
/// <summary>
/// Base manager class
/// Base manager class
/// </summary>
/// <typeparam name="T"></typeparam>
public class ColyseusManager<T> : MonoBehaviour
Expand All @@ -15,7 +14,7 @@ public class ColyseusManager<T> : MonoBehaviour
/// Reference to the Colyseus settings object.
/// </summary>
[SerializeField]
protected ColyseusSettings _colyseusSettings;
protected static ColyseusSettings _colyseusSettings;

// Getters
//==========================
Expand All @@ -30,7 +29,7 @@ public class ColyseusManager<T> : MonoBehaviour
/// </summary>
public string ColyseusServerAddress
{
get { return _colyseusSettings.colyseusServerAddress; }
get { return _colyseusSettings.colyseusServerAddress; }
}

/// <summary>
Expand Down Expand Up @@ -84,6 +83,7 @@ private void InitializeInstance()
}

Instance = GetComponent<T>();
_colyseusSettings = ScriptableObject.CreateInstance<ColyseusSettings>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally the settings object was designed to be able to be assigned in editor so devs could have multiple settings objects (local, dev, staging, prod, etc). @lpsandaruwan can you confirm that this doesn't break that functionality? Or if it does/needs to thats ok too, we just need to be able to provide an explanation/workaround for people who use that feature.

}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions Assets/Colyseus/Runtime/Scripts/Models/ColyseusClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using LucidSightTools;
using Settings;
using UnityEngine;

// ReSharper disable InconsistentNaming
Expand Down
23 changes: 12 additions & 11 deletions Assets/Colyseus/Runtime/Scripts/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.IO;
using GameDevWare.Serialization;
using LucidSightTools;
using Settings;

namespace Colyseus
{
Expand All @@ -32,24 +33,24 @@ public async Task<string> Request(string uriMethod, string uriPath, string uriQu
using (UnityWebRequest req = new UnityWebRequest())
{
req.method = uriMethod;

req.url = uriBuilder.Uri.ToString();
// Send JSON on request body
if (data != null)
{
req.uploadHandler = data;
}

foreach (KeyValuePair<string, string> pair in _serverSettings.HeadersDictionary)
{
req.SetRequestHeader(pair.Key, pair.Value);
}

if (!string.IsNullOrEmpty(Token))
{
req.SetRequestHeader("Authorization", "Bearer " + Token);
}

// req.uploadHandler = new UploadHandlerRaw(bytes);
req.downloadHandler = new DownloadHandlerBuffer();
await req.SendWebRequest();
Expand All @@ -72,9 +73,9 @@ public async Task<string> Request(string uriMethod, string uriPath, string uriQu
throw new Exception(req.error);
}
}

string json = req.downloadHandler.text;

return json;
} ;
}
Expand All @@ -94,26 +95,26 @@ public async Task<string> Request(string uriMethod, string uriPath, Dictionary<s
// Send JSON options on request body
MemoryStream jsonBodyStream = new MemoryStream();
Json.Serialize(options, jsonBodyStream); //TODO: Replace GameDevWare serialization

req.uploadHandler = new UploadHandlerRaw(jsonBodyStream.ToArray())
{
contentType = "application/json"
};
}

foreach (KeyValuePair<string, string> pair in _serverSettings.HeadersDictionary)
{
req.SetRequestHeader(pair.Key, pair.Value);
}

if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
req.SetRequestHeader(header.Key, header.Value);
}
}

req.downloadHandler = new DownloadHandlerBuffer();
await req.SendWebRequest();

Expand All @@ -135,7 +136,7 @@ public async Task<string> Request(string uriMethod, string uriPath, Dictionary<s
throw new Exception(req.error);
}
}

return req.downloadHandler.text;
};
}
Expand Down
5 changes: 5 additions & 0 deletions Assets/Colyseus/Runtime/Scripts/Serializer/Schema/Schema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,11 @@ public Action OnChange (OnChangeEventHandler handler)
return () => __callbacks.OnChange -= handler;
}

public void AddToOnChange(OnChangeEventHandler handler)
{
__callbacks.OnChange += handler;
}

/// <summary>
/// Attaches a callback that is triggered whenever this Schema instance has been removed from the server.
/// </summary>
Expand Down
Loading