I use the following script to rotate the Player Controller around the Y-axis of another flat cylinder’s game object. The script is intended to work similar to a merry-go-round.
I have this script on my Player Controller GO which has a box collider that is a trigger.
using UnityEngine;
public class RotatePlayer : MonoBehaviour
{
private bool isInsideCylinder = false;
private Transform cylinderTransform;
public float rotationSpeed = 20.0f; // Adjust this value for the desired rotation speed.
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Cylinder"))
{
isInsideCylinder = true;
cylinderTransform = other.transform;
Debug.Log("inside cylinder");
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Cylinder"))
{
isInsideCylinder = false;
cylinderTransform = null;
}
}
private void Update()
{
if (isInsideCylinder)
{
// Rotate the player around the Y-axis of the cylinder.
// You can adjust the rotation speed as needed.
// Calculate the rotation angle based on the time.
float rotationAngle = rotationSpeed * Time.deltaTime;
// Rotate the player around the center of the cylinder's Y-axis.
transform.RotateAround(cylinderTransform.position, Vector3.up, rotationAngle);
}
}
}
If I run the game in the unity editor and the player collider contacts the “Cylinder” collider the player spins about it’s own Y-axis. This is not what is supposed to happen.
If I open the RotatePlayer script while the game is still running in the unity editor and re-save the script. I do NOT making any changes to the script. Just re-save it. Then the editor automatically reloads the script assemblies and then the script behaves correctly.
Serialized fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:
what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)
what may be saved with the prefab
what may be saved with the prefab override(s)/variant(s)
what may be saved in the scene and not applied to the prefab
what may be changed in the scene and not yet saved to disk
what may be changed in OnEnable(), Awake(), Start(), or even later
Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.
Thanks for the links @ Kurt-Dekker. I read through them and realized that some variables must have been stuck from all the changes and reworking of the code. I ended up removing the player prefab and adding it back in and it seems to work for now.