Search Unity

Changing the cubes colour over the network

Discussion in 'Multiplayer' started by markpollard1, May 27, 2017.

  1. markpollard1

    markpollard1

    Joined:
    Apr 1, 2010
    Posts:
    70
    I have a cube already in the scene with a network identity on it i have not got anything tick in its propities.
    I want to have the player come to it and press e to change the colour on it. Is this the correct way cause its not working.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Networking;
    5. using UnityEngine.UI;
    6.  
    7. public class ColourChangingCube : NetworkBehaviour {
    8.  
    9.   private NetworkIdentity playerIdentity = null;
    10.   public bool isTriggered = false;
    11.   public Text interactText;
    12.  
    13.   private Renderer cubeRenderer;
    14.  
    15.   void Awake()
    16.   {
    17.     GetComponent<Renderer>();
    18.   }
    19.  
    20.   void OnTriggerEnter(Collider collider)
    21.   {
    22.  
    23.     ///check that is is a player
    24.     if(collider.gameObject.tag == "Player")
    25.     {
    26.       isTriggered = true;
    27.     }
    28.   }
    29.  
    30.   void Update()
    31.   {
    32.     if(isTriggered)
    33.     {
    34.       interactText.enabled = true;
    35.       if(Input.GetKeyDown(KeyCode.E))
    36.       {
    37.         CmdChangeCubeColour();
    38.         print("triggered");
    39.       }
    40.  
    41.     }
    42.     else
    43.     {
    44.       interactText.enabled = false;
    45.     }
    46.   }
    47.  
    48.   void OnTriggerExit(Collider collider)
    49.   {
    50.     if(collider.gameObject.tag == "Player")
    51.     {
    52.       isTriggered = false;
    53.     }
    54.   }
    55.  
    56.  
    57.   [Command]
    58.   void CmdChangeCubeColour()
    59.   {
    60.     RpcColourUpdate(this.gameObject);
    61.   }
    62.  
    63.   [ClientRpc]
    64.   void RpcColourUpdate(GameObject go)
    65.   {
    66.     cubeRenderer = go.GetComponent<Renderer>();
    67.  
    68.     print("called");
    69.     if(cubeRenderer.material.color == Color.white)
    70.     {
    71.       print("turn green");
    72.       cubeRenderer.material.color = Color.green;
    73.     }
    74.     else
    75.     {
    76.       print("turn white");
    77.       cubeRenderer.material.color = Color.white;
    78.     }
    79.   }
    80.  
    81.  
    82. }