Hello there,
I am IT student and I’m messing around Unity, making TPS style game. From time to time, my CameraMovementScript seems to crash and transform.position returning local position of following pivot, as a result - camera is following global (0,0,0) point instead of player.
To fix this I only need to restart Unity. Then it happens again in few times “Play” clicked.
I basically used GameObject.Find(“Parent”).transform.Find(“Child”).position to work around what I believe to be a similar issue.
My similar, strange problem is that a prefab (“Boss”) contains a child (“CameraAnchor”) and GameObject.Find(“CameraAnchor”) would sometimes, every now and then, return (0,4.5,0) as transform.position, which is actually the localPosition. It seemed to happen sometimes when restarting the scene, but not reliably. Usually transform.position would return the expected global position of (230, 4.5, 0)
I was able to work around this strange problem by grabbing GameObject.Find(“Boss”), and then using transform.Find(“CameraAnchor”)
Here is my mess of a function I eventually cobbled together. Most code probably can’t use “x > 1” as a “valid” position, but it works for me because a Boss is never at the beginning of a level
public void LockCamera(Vector2 lockPosition)
{
// This is normal, everything is fine
if (lockPosition.x >= 1)
{
_isPositionLocked = true;
_lockPosition = lockPosition;
return;
}
// Uh oh, Unity done goofed and gave us the localPosition for some reason...
Debug.Log("INVALID CameraScript.LockCamera(lockPosition = " + lockPosition);
GameObject bossObject = GameObject.Find("Boss");
// Serious problem here
if (bossObject == null)
{
Debug.Log("Unable to Find Boss object, aborting LockCamera");
return;
}
Debug.Log("Boss at " + bossObject.transform.position);
_lockPosition = bossObject.transform.position;
if (_lockPosition.x >= 1)
{
_isPositionLocked = true;
}
// We can try to get the CameraAnchor ourselves
Transform cameraAnchorObjectTransform = bossObject.transform.Find("CameraAnchor");
if (cameraAnchorObjectTransform == null)
{
// Well, we tried.
Debug.Log("Unable to Find CameraAnchor, using Boss if able");
return;
}
else if (cameraAnchorObjectTransform.position.x >= 1)
{
Debug.Log("Found CameraAnchor at " + cameraAnchorObjectTransform.position);
_lockPosition = cameraAnchorObjectTransform.position;
_isPositionLocked = true;
return;
}
Debug.Log("Found CameraAnchor at INVALID, using Boss if able " + cameraAnchorObjectTransform.position);
}