- Home /
Finding objects on scene change
I have a camera, that follows the player. Both of them are set to not get destroyed on scene change. In each scene, I also have objects that's transform sets the limit of the camera's movement.
However, when changing the scene, the camera loses it's reference to the old objects, but doesn't replace it with the ones in the active scene. How would I make it relook the object references on scene load?
public class CameraLimits : MonoBehaviour
{
[SerializeField]
GameObject limitL;
[SerializeField]
GameObject limitR;
[SerializeField]
GameObject limitB;
void Update()
{
transform.position = new Vector3(Mathf.Clamp
(transform.position.x, limitL.transform.position.x, limitR.transform.position.x),
Mathf.Clamp(transform.position.y, limitB.transform.position.y, 100), transform.position.z);
}
}
Answer by CodesCove · Dec 10, 2021 at 06:53 PM
One way to solve this is to make the position limit as ScriptableObject asset.
Idea is that you make a (for example) Position : ScriptableObject class that has a public GameObject variable.
Then you make a Monobehaviour Component where you can store the above Position asset (asset is instance of SO) reference. You attach this Component to the GameObjects that you want to use as position limit. In this component you also make the GameObject to register to the Position SriptableObject's GameObject variable whenever it's instantiated (in Awake for example).
In the CameraLimits script you don't look for the position limits straight from the GameObject but via Position ScirptableObject asset and the GameObject reference in there.
In this way you always have the correct GameObject reference, but this time it just goes via the Scriptable object.
check here short intro to ScriptableObject https://docs.unity3d.com/Manual/class-ScriptableObject.html