Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize: AddTo MonoBehaviour #80

Merged
merged 2 commits into from
Jan 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/LitMotion/Assets/LitMotion/Runtime/MotionHandleExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace LitMotion
Expand Down Expand Up @@ -70,6 +71,22 @@ public static MotionHandle AddTo(this MotionHandle handle, Component target)
return handle;
}

#if UNITY_2022_2_OR_NEWER
/// <summary>
/// Link the motion lifecycle to the target object.
/// </summary>
/// <param name="handle">This motion handle</param>
/// <param name="target">Target object</param>
public static MotionHandle AddTo(this MotionHandle handle, MonoBehaviour target)
{
target.destroyCancellationToken.Register(() =>
{
if (handle.IsActive()) handle.Cancel();
}, false);
return handle;
}
#endif

static TComponent GetOrAddComponent<TComponent>(GameObject target) where TComponent : Component
{
if (!target.TryGetComponent<TComponent>(out var component))
Expand Down
17 changes: 17 additions & 0 deletions src/LitMotion/Assets/LitMotion/Tests/Runtime/AddToTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,22 @@ public IEnumerator Test_AddTo()
Object.DestroyImmediate(obj);
Assert.IsTrue(canceled);
}

[UnityTest]
public IEnumerator Test_AddTo_MonoBehaviour()
{
var canceled = false;
var obj = new GameObject("Target");
var behaviour = obj.AddComponent<TestComponent>();
var handle = LMotion.Create(0f, 1f, 2f)
.WithOnCancel(() => canceled = true)
.RunWithoutBinding()
.AddTo(behaviour);
yield return new WaitForSeconds(0.1f);
Object.DestroyImmediate(obj);
Assert.IsTrue(canceled);
}

public sealed class TestComponent : MonoBehaviour { }
}
}