80 lines
1.7 KiB
C#
80 lines
1.7 KiB
C#
using System.Threading;
|
|
using KitsuneCafe.Sys;
|
|
using R3;
|
|
using UnityEngine;
|
|
|
|
namespace KitsuneCafe.Entities
|
|
{
|
|
public class ParentToPlatform : MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private Raycaster raycaster;
|
|
|
|
[SerializeField]
|
|
private Transform self;
|
|
|
|
[SerializeField]
|
|
private Transform parent;
|
|
|
|
private Transform empty;
|
|
|
|
public Transform Parent => empty.parent;
|
|
|
|
private CancellationTokenSource disableCancellationTokenSource;
|
|
private CancellationToken disableCancellationToken => disableCancellationTokenSource.Token;
|
|
|
|
private void Reset()
|
|
{
|
|
self = transform;
|
|
parent = self.parent;
|
|
}
|
|
|
|
private void Awake()
|
|
{
|
|
empty = new GameObject($"Empty {self.name} Parent").transform;
|
|
|
|
var r = parent == null ? self : parent;
|
|
empty.SetParent(r.parent);
|
|
r.SetParent(empty);
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
disableCancellationTokenSource = new();
|
|
|
|
Observable.ObservePropertyChanged(raycaster, rc => rc.Collisions)
|
|
.Subscribe(_ =>
|
|
{
|
|
if (GetParent(out var newParent))
|
|
{
|
|
empty.SetParent(newParent, true);
|
|
}
|
|
else
|
|
{
|
|
empty.SetParent(parent, true);
|
|
}
|
|
})
|
|
.RegisterTo(disableCancellationToken);
|
|
}
|
|
|
|
private bool GetParent(out Transform parent)
|
|
{
|
|
if (raycaster.IsColliding
|
|
&& raycaster.TryGetClosestHit(out var hit)
|
|
&& hit.transform != null
|
|
&& !hit.transform.gameObject.isStatic)
|
|
{
|
|
parent = hit.transform;
|
|
return true;
|
|
}
|
|
|
|
parent = default;
|
|
return false;
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
disableCancellationTokenSource.Cancel();
|
|
}
|
|
}
|
|
}
|