using System;
using UnityEditor;
using UnityEngine;
namespace Unity.Tutorials.Core.Editor
{
///
/// Criterion for checking that Scene View Camera has moved.
///
public class SceneViewCameraMovedCriterion : Criterion
{
[NonSerialized]
bool m_InitialPositionInitialized = false;
[NonSerialized]
Vector3 m_InitialCameraPosition;
[NonSerialized]
Quaternion m_InitialCameraOrientation;
///
/// Starts testing of the criterion.
///
public override void StartTesting()
{
UpdateInitialCameraPositionIfNeeded();
UpdateCompletion();
EditorApplication.update += UpdateCompletion;
}
void UpdateInitialCameraPositionIfNeeded()
{
if (m_InitialPositionInitialized)
return;
if (SceneView.lastActiveSceneView == null)
return;
m_InitialPositionInitialized = true;
m_InitialCameraPosition = SceneView.lastActiveSceneView.camera.transform.position;
m_InitialCameraOrientation = SceneView.lastActiveSceneView.camera.transform.localRotation;
}
///
/// Stops testing of the criterion.
///
public override void StopTesting()
{
EditorApplication.update -= UpdateCompletion;
m_InitialPositionInitialized = false;
}
///
/// Evaluates if the criterion is completed.
///
///
protected override bool EvaluateCompletion()
{
if (SceneView.lastActiveSceneView == null)
return false;
UpdateInitialCameraPositionIfNeeded();
var currentPosition = SceneView.lastActiveSceneView.camera.transform.position;
var currentOrientation = SceneView.lastActiveSceneView.camera.transform.localRotation;
return m_InitialCameraPosition != currentPosition || m_InitialCameraOrientation != currentOrientation;
}
///
/// Auto-completes the criterion.
///
/// True if the auto-completion succeeded.
public override bool AutoComplete()
{
// NOTE SceneView.lastActiveSceneView.camera.transform.position should not be used for moving the camera,
// must use the SceneView.lastActiveSceneView.pivot instead, https://forum.unity.com/threads/moving-scene-view-camera-from-editor-script.64920/#post-415327
SceneView.lastActiveSceneView.pivot = m_InitialCameraPosition + Vector3.back;
return true;
}
}
}