How to get the local player?

Started by Yoku 4 posts 164 views

Reply on sbox.game
  1. edited Jun 2026 #1
    Yoku 5
    I need to access the player from inside a prefab to find a component on the player and then use it later.


    The script is attached to the prefab. If I try to do this via GameObject and Property, the prefab won't see the reference from the scene.

    var player = e.Source?.GameObject; only works for the IPressable interface. 

    I've been looking through the documentation and can't find anything. 
    Does anyone know how to access the local player?

    edited:
     
    I ended up doing it like this:

    var player = Scene.GetAllComponents<PlayerController>()
        .FirstOrDefault( p => !p.IsProxy );

    I'm not sure if this is the "correct" way, but it works.
  2. #2
    Omjihn 855
    I would have added a [Property] reference, in the script directly, if possible in your context.
    It avoid runtime search.

    Edit:

     The script is attached to the prefab. If I try to do this via GameObject and Property, the prefab won't see the reference from the scene. 

    Ah my bad lol
  3. #3
    xraybeesx 1,160
    I use something like this:  
    [Property] public SkinnedModelRenderer player { get; set; }
     If not animated this:
     
    [Property] public ModelRenderer player { get; set; }
     You then drag and drop the player in the public slot. This accesses the player model, if you need to acces the rigidbody, or character controller use:
     
    [Property] public CharacterController player { get; set; }
      
    [Property] public Rigidbody player { get; set; }
    Depending on whatever component your trying to call just use that, and just drag the player in the prefab into the public slot.
  4. #4
    inhuman 2,255
    Answers to this topic sums up why majority of s&box playerbase prefer idle games I guess