net writes valid ent and receives null


I’m writing a new prop hunt

I’m trying to send and entity to the client, I print out the ent’s class on the server before sending and it’s valid
when I ( try to ) print the ent’s class on the client in the receive hook it says it’s a NULL entity.

this happens before selecting the first prop

In the SetPlayerProp function:

and receive on the client:

Doing this resolves the issue:
timer.Simple( 2, function( ) SetPlayerProp( ply, ply.chosenProp ); end )

How do I fix this without a timer?

It takes a little bit of time for the server to tell the client that an entity has been created. What you can do is send the :EntIndex() and use it with Entity() on the client and only do stuff when it doesn’t return NULL.

There’s probably a better way, but one possible solution you could use an OnEntityCreated hook on the client, which will ensure the entity has been created before trying to do anything with it.

The downside is if you just leave the hook there it’ll get called for every entity that gets created as it gets created.

So, one alternative that uses ralle105’s suggestion is to use the message sent from the server to make the client create an OnEntityCreated hook. When any entity gets created during that time, check to see if the entity’s EntIndex matches the one you received from the server. If it does, perform your stuff and then remove the OnEntityCreated hook so it doesn’t get needlessly called anymore.

Here’s an example:

net.Start( "Prop Update" )
    net.WriteVector( tHitboxMax )
    net.WriteVector( tHitboxMin )
    net.WriteUInt( ply.chosenProp:EntIndex(), 8 ) -- send the entity's index instead
    net.WriteUInt( ply.lastPropChange, 32 )
net.Send( ply )

-- In
net.Receive( "Prop Update", function( length )
    local tHitboxMax = net.ReadVector()
    local tHitboxMin = net.ReadVector()
    LocalPlayer():SetHull( tHitboxMin, tHitboxMax )
    LocalPlayer():SetHullDuck( tHitboxMin, tHitboxMax )

    LocalPlayer().chosenPropIndex = net.ReadUInt(8) -- get the entity's index instead
    LocalPlayer().lastPropChange = net.ReadUInt(32)

    local propHeight = tHitboxMax.z - tHitboxMin.z
    LocalPlayer().propHeight = propHeight

    hook.Add( "OnEntityCreated", "Get Player Prop", function( ent )
        if ( LocalPlayer().chosenPropIndex and LocalPlayer().chosenPropIndex == ent:EntIndex() ) then
            -- do your stuff here, like:
            LocalPlayer().chosenProp = ent
            hook.Remove( "OnEntityCreated", "Get Player Prop" ) -- no longer needed, so remove it
    end )
end )

I gave you a heart because I love you

I didn’t know about this “OnEntityCreated” :slight_smile:

Everything is perfect now!