Hello,
I want my player to be able to do a 180 flip when he is near a chair. So that he will sit baiscly.
I’m using the OnTriggerEnter and Exit just like that:
public class ChairScript : MonoBehaviour
{
public ExtraPlayerButtonConfiguration extraPlayerButtonConfiguration;
public void Start()
{
extraPlayerButtonConfiguration = gameObject.GetComponent<ExtraPlayerButtonConfiguration>();
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
if (other.gameObject.TryGetComponent(out ChairScript chairScript))
{
extraPlayerButtonConfiguration.closestChair = this;
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
if (other.gameObject.TryGetComponent(out ChairScript chairScript))
{
if (extraPlayerButtonConfiguration.closestChair == this)
{
extraPlayerButtonConfiguration.closestChair = null;
}
}
}
}
}
And I’m calling it inside this function:
public class ExtraPlayerButtonConfiguration : NetworkBehaviour
{
[SerializeField]
private GameObject playerXRRig;
private InputAction sitOnChair;
private Transform chairTransform;
private Transform playerTransform;
public ChairScript closestChair;
// Start is called before the first frame update
void Start()
{
var gameplayActionMapLeftHand = playerControls.FindActionMap("XRI LeftHand");
sitOnChair = gameplayActionMapLeftHand.FindAction("Sit");
sitOnChair.performed += OnSitOnChair;
sitOnChair.Enable();
}
//Sit On Chair Action calling.
public void OnSitOnChair(InputAction.CallbackContext context)
{
if (IsClient && IsOwner)
{
if (closestChair)
{
// Rotate the player and snap him to the chair
playerTransform = chairTransform.transform;
playerTransform.rotation *= Quaternion.Euler(0, 180f, 0);
playerTransform.position = chairTransform.position - new Vector3(0, 0, 1.0f);
}
}
}
But my code never enter inside
if (other.gameObject.TryGetComponent(out ChairScript chairScript))
{
extraPlayerButtonConfiguration.closestChair = this;
}
I have no clue what I’m doing wrong or why it doesn’t want to work. Could it be that the second script is NetworkBehaviour because I’m using Netcode for GameObject for my multiplayer VR app? Or what could be the problem?
Does your player object have the ChairScript object because if it doesn’t it wont enter that if statement. Since you are not using that ChairScript component inside the if function you might not be able to need that check at all unless you remove and add the chaircomponent on the player during runtime.
Btw instead of using other.tag you could use the compare function: Unity - Scripting API: Component.CompareTag . Might not have a big impact on performance on your current project but is good practise to use that becaue it allocates less memory.