Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Get isLocalPlayer in child object

Discussion in 'Multiplayer' started by Lexeon, May 15, 2016.

  1. Lexeon

    Lexeon

    Joined:
    Apr 22, 2016
    Posts:
    23
    So, I have a child object that has some code that needs to access isLocalPlayer. The parent is the one with the network identity, so I cannot access the isLocalPlayer variable directly. I made a script attached to the player that will store the isLocalPlayer variable, and the child can access it by using GetComponent. However, that is being called every update, and I'm sure that so many GetComponent calls per update will cause some kind of overhead. Is there any other way to check and see isLocalPlayer without so many calls?
     
  2. Oshroth

    Oshroth

    Joined:
    Apr 28, 2014
    Posts:
    99
    Cache the reference to the script instead. Anyway, you can access the isLocalPlayer variable through the NetworkIdentity on the parent object since NetworkBehaviour.isLocalPlayer is just a property calling NetworkIdentity.IsLocalPlayer.
    Code (CSharp):
    1. NetworkIdentity netview;
    2.  
    3. void Start() {
    4.   netview = GetComponentInParent<NetworkIdentity>();
    5. }
    6.  
    7. void Update() {
    8.   if(netview != null && netview.isLocalPlayer) {
    9.     //Do Something
    10.   }
    11. }
     
  3. Lexeon

    Lexeon

    Joined:
    Apr 22, 2016
    Posts:
    23

    Caching was probably first thing I did, however it did not work, since it made everyone a localplayer even if the player object did not belong to them. I also got the parent NetworkIdentity variable, but it produced the same result. I have a workaround in mind, so I will try that and see if that works whenever I get back.
     
  4. Lexeon

    Lexeon

    Joined:
    Apr 22, 2016
    Posts:
    23
    I reloaded my scripts, and now it somehow works. Thanks.