Custom Player Scripts

Previously, we have mentioned 2 types of Lua scripts. One type is Lua scripts managed by ParaScript, and the other type is Lua scripts managed by ParaScriptLoader. Lua scripts managed by ParaScript are mounted to GameObjects to control objects in a scene or objects cloned using GameObject.Instantiate. However, how can we control GameObjects corresponding to players in a World? Players' GameObjects in a World are created by ParaSpace after a scene is loaded and a network is initialized. We need an additional mechanism to mount ParaScript components to players' GameObjects.

The ParaPlayerScriptsManager component can manage a group of ParaScript components. When a player's GameObject is created, this component can clone a ParaScript component and mount it to the player's GameObject.

For example, as shown in the following figure, create an empty GameObject in the scene, add the ParaPlayerScriptsManager component, and create and drag the PlayerController.lua file into the Inspector panel. Then a Para Script component will be generated and mounted to this Lua script. Set the number of Player Scripts and drag the Para Script component into Element 0.

After completing the preceding operations, when a player is created in the scene, the PlayerController.lua script will be cloned and mounted to the GameObject of the player.

The following is an example code in the PlayerController.lua file that explains how to get the player ID.

-- PlayerController.lua 

---@varSync playerHP:int = 100;

-- Start is called before the first frame update
function OnNetSpawned()
    -- if this script is attach on Player's GameObject then self.paraPlayer is not nil
    print("PlayerController OnNetSpawned ",self.paraPlayer,self.gameObject);

    if self.paraPlayer.isMaster then
       print("PlayerController master player playerID:",self.paraPlayer.playerID);
    end

    -- you can use self.paraPlayer to quickly access functions in ParaPlayer class
    -- self.paraPlayer:PlayAnimation()
end

Note

  1. After you mount the ParaPlayerScriptsManager component to a GameObject, all Lua scripts of the ParaScript components mounted to that object will be ignored. They will not be executed when a scene is being loaded.
  2. ParaScript.paraPlayer returns a valid ParaPlayer object only when a ParaScript component is mounted to the player's GameObject. In other cases, nil will be returned.