CharacterSelection.cs 1.7 KB
Newer Older
cann-alberto's avatar
cann-alberto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using UnityEngine;
using Mirror;

namespace Mirror.Examples.CharacterSelection
{
    public class CharacterSelection : NetworkBehaviour
    {
        public Transform floatingInfo;

        [SyncVar]
        public int characterNumber = 0;

        public TextMesh textMeshName;
        [SyncVar(hook = nameof(HookSetName))]
        public string playerName = "";

        void HookSetName(string _old, string _new)
        {
            //Debug.Log("HookSetName");
            AssignName();
        }
        
        [SyncVar(hook = nameof(HookSetColor))]
        public Color characterColour;
        private Material cachedMaterial;
        public MeshRenderer[] characterRenderers;

        void HookSetColor(Color _old, Color _new)
        {
            //Debug.Log("HookSetColor");
            AssignColours();
        }

        public void AssignColours()
        {
            foreach (MeshRenderer meshRenderer in characterRenderers)
            {
                cachedMaterial = meshRenderer.material;
                cachedMaterial.color = characterColour;
            }
        }

        void OnDestroy()
        {
            if (cachedMaterial) { Destroy(cachedMaterial); }
        }

        public void AssignName()
        {
            textMeshName.text = playerName;
        }

        // To change server controlled sync vars, clients end Commands, and the hooks will fire
        // Although not used in this example, we could change some character aspects without replacing current prefab.
        //[Command]
        //public void CmdSetupCharacter(string _playerName, Color _characterColour)
        //{
        //    playerName = _playerName;
        //    characterColour = _characterColour;
        //}
    }
}