Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Collections;
- public class MoveObject : NetworkBehaviour {
- public GameObject ourObjectToMove; //Public so we can see it in the inspector, but making this private won't hurt you.
- RaycastHit hit; //Will contain the data from the ray we shoot in Update()
- void Start () {
- if (!isLocalPlayer)
- this.enabled = false; //This is just a temporary fix to make sure that our script isn't active on this object if we aren't the local player (so that when we press space it doesn't send a command from every player!)
- //You should make a seperate script to do this in the future however.
- }
- void Update () {
- //I don't know how you want to determine what object gets affected. Here's one solution, but this can be applied to pretty much anything.
- if(Input.GetMouseButtonDown(0)) //We click with the left mouse button
- {
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Shoot a ray out from our mouse
- if(Physics.Raycast(ray, out hit)) //If our ray hits something
- {
- ourObjectToMove = hit.transform.gameObject;
- Debug.Log("We have clicked on " + hit.transform.name + " and made it our selected object!");
- }
- }
- if (Input.GetKeyDown(KeyCode.Space) && ourObjectToMove != null) //We have an object to move and we have pressed the space bar.
- {
- print("Space pressed");
- CmdMoveObject(10, Vector3.up, ourObjectToMove.GetComponent<NetworkIdentity>().netId); //We need to get the netID of whatever object we are trying to move.
- }
- }
- [Command]
- void CmdMoveObject(float power, Vector3 direction, NetworkInstanceId netid)
- {
- RpcMoveObject(power, direction, netid); //Commands are only called on the server. We want this to be replicated onto all clients as well, so we call a ClientRPC.
- }
- [ClientRpc]
- void RpcMoveObject(float power, Vector3 direction, NetworkInstanceId netid) //It gets passed the same arguments.
- {
- GameObject ourThingToMove = ClientScene.FindLocalObject(netid); //This will have each client get a reference to the thing we want to move by searching for its netID.
- ourThingToMove.GetComponent<Rigidbody>().AddForce(power * direction, ForceMode.Impulse); //Now we can apply the force!
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment