I’m trying to learn events in order to make my code cleaner and I’m playing with delegates and events to move my camera when a player collides with a certain portion of the level. Here is some code that works. But what I notice is that you can only invoke one method from an event? I feel like this shouldn’t be the case. Anyway, the intent is that based on info about the collision the publisher should call either MoveCameraUp or MoveCameraRight. But this approach requires that both functions will be called. Is it possible to call only the one i want based on some collision conditions?
public class CameraTransitionObjScript : MonoBehaviour // attached to block
{
public delegate void MoveCamera();
public static event MoveCamera moveCamera;
private void OnTriggerEnter2D(Collider2D col)
{
moveCamera?.Invoke();
}
}
and here is the camera. What i’m trying to also do is make only the camera control it’s own movement, not have other objects control it’s movements (only because I heard that’s bad because it creates dependencies)
public class MoveTransition : MonoBehaviour // attached to main camera
{
void OnEnable()
{
CameraTransitionObjScript.moveCamera += MoveCameraRight;
CameraTransitionObjScript.moveCamera += MoveCameraUp;
}
private void MoveCameraRight()
{
var currentPosition = transform.position;
transform.position += new Vector3(84f, 0f, 0f);
}
private void MoveCameraUp()
{
var currentPosition = transform.position;
transform.position += new Vector3(0f, 45f, 0f);
}
}