GetComponent by Tag instead of variable reference

I have a few places in my code where I am using a public player game object reference (playerObject) to run GetComponent to check player’s raycast to see if the player is looking at the trigger, and to see whether the player is holding a key, etc.

For ease of use I would like to get rid of the public player game object variable, and just use Player tags, and then every Player entering the trigger can have a GetComponent run on it. My question is, how would I do this? I’m confused about how to call a GetComponent based on Tag without a specific object reference. I searched for this but could not find an answer.

For clarity; I want to get rid of playerObject entirely, and just run a GetComponent on everything tagged “Player.”

void OnTriggerStay(Collider playerObject) 
	{	
		if (playerObject.GetComponent<Player_Raycast>().lookAtUseItem)
			{
				triggerActive = true;
			}
			else
			{
				triggerActive = false;
			}

		if (playerObject == null) 
			{
				Debug.LogWarning("No player object set for the door trigger!");
			}

		//If there is a doorKey and a playerObject set, and the doorKey is a child object of the Player, then player has key.
		if (doorKey != null && playerObject != null && doorKey.transform.IsChildOf(playerObject.transform))			
			
			{
				playerHasKey = true;
			}
		
			//If the current state is locked and the player has the key...
			if (_curTrigState == triggerState.trigLocked && playerHasKey)
				
			//Then we set the current state to unlockable
			{
			_curTrigState = triggerState.trigUnlockable;
			}
	}

there is no GetComponent<>() based on tag, but you can do something like:

if (playerObject.tag = "whatever")
{
   //...
}

after the null check, of course… that should be the first thing you do, before any GetComponent<>() defensive programming isn’t such a bad thing. prevention being better than cure and all that :wink:

Ah, yeah, I tried just using CompareTag on “Collider other” and that works. Don’t need a reference variable. Over-thinking things as usual. :slight_smile:

void OnTriggerStay(Collider other) 
{	

	if (other.gameObject.CompareTag("Player"))
	{

		//playerObject = other.gameObject;
		if (other.GetComponent<Player_Raycast>().lookAtUseItem)
		{
			triggerActive = true;
		}
		else
		{
			triggerActive = false;
		}
		
		//If there is a doorKey and a playerObject set, and the doorKey is a child object of the Player, then player has key.
		if (doorKey != null && doorKey.transform.IsChildOf(other.transform))				
		{
			playerHasKey = true;
		}
		
		//If the current state is locked and the player has the key...
		if (_curTrigState == triggerState.trigLocked && playerHasKey)
			
			//Then we set the current state to unlockable
		{
			_curTrigState = triggerState.trigUnlockable;
		}
	}