GitHub | Documentation | Become a Patron

[Unity] KeyNotFoundException



  • I get an empty list when processing the "Add" operation. The Unity example shows how the X and Y value is received though. This is what my code looks like. What could I be missing?

    client.

    room.Listen("players/:id", OnPlayerChange);
    
    private void OnPlayerChange(DataChange change)
    {
    	Debug.Log($"OnPlayerChange: {change.operation} > {change.path["id"]} > {change.value}");
    
    	if (change.operation == "add")
    	{
    		// extract data
    		IndexedDictionary<string, object> value = (IndexedDictionary<string, object>)change.value;
    
    		// this prints (0) - no values in the dictionary
    		Debug.LogWarning($"There are {value.Count} entries");
    
    		string id = change.path["id"];
    		Vector2 pos = new Vector3(Convert.ToSingle(value["x"]), Convert.ToSingle(value["y"]));
    		int hp = Convert.ToInt32(value["hp"]);
    
    		// create and add to list of players
    		gameController.CreateActor(id, pos, hp);
    	}
    
    	else if (change.operation == "remove")
    	{
    		// remove player
    		gameController.RemoveActor(change.path["id"]);
    	}
    }
    

    server

    import { Client, Room, nosync } from "colyseus";
    
    export class Player
    {
        x: number;
        y: number;
        hp: number;
    
        @nosync client: Client;
        @nosync room: Room;
        
        constructor(client: Client, room: Room) 
        {
          this.client = client;
          this.room = room;
        }    
    }
    
    import { EntityMap, Client, Room } from "colyseus";
    import { Player } from "./Player";
    
    export class GameState
    {
        players: EntityMap<Player> = {};
       
        addPlayer(client: Client, room: Room)
        {
            this.players[client.sessionId] = new Player(client, room);
        }
        
        removePlayer(client: Client)
        {
            delete this.players[client.sessionId];
        }
        
        performAction(client: Client, action: string)
        {
            if (action === "left") 
            {
                this.players[client.sessionId].x -= 1;
            } 
            else if (action === "right") 
            {
                this.players[client.sessionId].x += 1;
            }
        }    
    }
    


  • Turns out I just needed to init the variables.

    export class Player
    {
        x: number = 0;
        y: number = 0;
        hp: number = 0;
    

Log in to reply
 

Looks like your connection to Colyseus Forum was lost, please wait while we try to reconnect.