slimabob

MoveObject.cs

Nov 11th, 2016
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System.Collections;
  4.  
  5. public class MoveObject : NetworkBehaviour {
  6.  
  7. public GameObject ourObjectToMove; //Public so we can see it in the inspector, but making this private won't hurt you.
  8.  
  9. RaycastHit hit; //Will contain the data from the ray we shoot in Update()
  10.  
  11. void Start () {
  12. if (!isLocalPlayer)
  13. 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!)
  14. //You should make a seperate script to do this in the future however.
  15. }
  16.  
  17. void Update () {
  18.  
  19. //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.
  20.  
  21. if(Input.GetMouseButtonDown(0)) //We click with the left mouse button
  22. {
  23. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Shoot a ray out from our mouse
  24. if(Physics.Raycast(ray, out hit)) //If our ray hits something
  25. {
  26. ourObjectToMove = hit.transform.gameObject;
  27. Debug.Log("We have clicked on " + hit.transform.name + " and made it our selected object!");
  28. }
  29. }
  30.  
  31. if (Input.GetKeyDown(KeyCode.Space) && ourObjectToMove != null) //We have an object to move and we have pressed the space bar.
  32. {
  33. print("Space pressed");
  34. CmdMoveObject(10, Vector3.up, ourObjectToMove.GetComponent<NetworkIdentity>().netId); //We need to get the netID of whatever object we are trying to move.
  35. }
  36. }
  37.  
  38. [Command]
  39. void CmdMoveObject(float power, Vector3 direction, NetworkInstanceId netid)
  40. {
  41. 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.
  42. }
  43.  
  44. [ClientRpc]
  45. void RpcMoveObject(float power, Vector3 direction, NetworkInstanceId netid) //It gets passed the same arguments.
  46. {
  47. 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.
  48. ourThingToMove.GetComponent<Rigidbody>().AddForce(power * direction, ForceMode.Impulse); //Now we can apply the force!
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment