#[Netcode] Getting reference to player

1 messages · Page 1 of 1 (latest)

rugged gulch
#

Hey so I am trying to add an interact button when the player is close to an npc, I got the logic working I just need to reference the player but if I reference the prefab it doesnt work because the networkmanager spawns the player as a clone. How can I get a reference to that clone?
Thanks in advance

    [SerializeField] private GameObject containerGameObject;
    [SerializeField] private PlayerInteract playerInteract;

    private void Update()
    {
        if (playerInteract.GetInteractableObject() != null)
        {
            Show();
        }
        else
        {
            Hide();
        }
    }

    private void Show()
    {
        containerGameObject.SetActive(true);
    }

    private void Hide()
    {
        containerGameObject.SetActive(false);
    }

I guess I can do that in update but its very expensive

        if (playerInteract == null)
        {
            GameObject player = GameObject.FindWithTag("Player");
            playerInteract = player.GetComponent<PlayerInteract>();
        }
#

what if I do something like a coroutine that checks if the player is spawned every second or so, would that be more optimized than using update?

ionic aurora
#

[]getref

livid hearthBOT
#

How to get a reference
"How do I access a variable from another script?" is usually one of the first questions we ask when learning Unity. Whether you are C# beginner or a C# professional, understanding the way Unity does things differently can be confusing.

🌳 If the objects are already present in the scene hierarchy...
... then you can use the SerializeField attribute on a field, and assign it by dragging the object which has the script you want to access onto the field slot. This also works if the two scripts are on the same object.

[SerializeField] private SomeScript someScript;

prefab If the objects are instantiated prefabs...
... then you can use a form of injection after you call Instantiate:
SomeScript.cs

public GameManager TheManager { get; set; }

GameManager.cs

var clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().TheManager = this;
ionic aurora
#

The second part is relevant for you. It's some kind of an injection once you instantiate the object.