Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MonoBehaviourとComponentDataの同期
using Unity.Entities;
using UnityEngine;
public class DisplayPlayerDistance : MonoBehaviour
{
DistanceFromPlayerAuthoring fromPlayer;
void Start()
{
fromPlayer = GetComponent<DistanceFromPlayerAuthoring>();
}
// Update is called once per frame
void Update()
{
Debug.Log(fromPlayer.Distance);
}
}
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using static Unity.Entities.ComponentType;
[DisallowMultipleComponent]
[RequiresEntityConversion]
public class DistanceFromPlayerAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
/// <summary> プレイヤーとの距離 </summary>
public float Distance { get; set; }
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new DistanceFromPlayer());
}
}
// DistanceFromPlayerをDistanceFromPlayerAuthoringに反映するシステム
[UpdateInGroup(typeof(InitializationSystemGroup))]
public class SetDistanceDataToAnimator : ComponentSystem
{
protected override void OnUpdate()
{
Entities.ForEach((DistanceFromPlayerAuthoring authoring, ref DistanceFromPlayer distance) => authoring.Distance = distance.Value);
}
}
/// <summary> PlayerTagを持つEntityとの距離 </summary>
[System.Serializable]
public struct DistanceFromPlayer : IComponentData
{
public float Value;
}
/// <summary>
/// PlayerTagとDistanceFromPlayerの距離をValueに格納するシステム
/// </summary>
public class DistanceCheckSystem : JobComponentSystem
{
EntityQuery playerQuery;
protected override void OnCreate()
{
playerQuery = GetEntityQuery(ReadOnly<PlayerTag>(), ReadOnly<LocalToWorld>());
RequireForUpdate(playerQuery);
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var playerPos = playerQuery.GetSingleton<LocalToWorld>().Position;
inputDeps = Entities
.ForEach((ref DistanceFromPlayer distance, in LocalToWorld pos) =>
{
distance.Value = math.distance(pos.Position, playerPos);
}).Schedule(inputDeps);
return inputDeps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.