119 lines
3.0 KiB
C#
119 lines
3.0 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
/// <summary>
|
|
/// Binds five pre-authored UI touch regions to the existing gameplay input path.
|
|
/// This script does not create runtime objects. You assign the region RectTransforms
|
|
/// in the inspector, and it ensures each one has an Image raycast target plus a
|
|
/// TrackTouchRegion configured with the matching track index.
|
|
/// </summary>
|
|
[DisallowMultipleComponent]
|
|
public class TrackTouchRegionLayoutController : MonoBehaviour
|
|
{
|
|
[Serializable]
|
|
public class RegionBinding
|
|
{
|
|
[Range(0, 4)]
|
|
public int trackIndex;
|
|
|
|
[Tooltip("Pre-authored UI region to bind. Assign in inspector.")]
|
|
public RectTransform regionObject;
|
|
|
|
[Tooltip("Optional debug tint. Alpha 0 keeps the region invisible while preserving raycasts.")]
|
|
public Color debugTint = new Color(1f, 1f, 1f, 0f);
|
|
}
|
|
|
|
[Header("Behavior")]
|
|
public bool bindOnStart = true;
|
|
public bool mobileOnly = true;
|
|
|
|
[Header("Prebound Regions")]
|
|
public RegionBinding[] regions = new RegionBinding[5];
|
|
|
|
private void Reset()
|
|
{
|
|
EnsureDefaultBindings();
|
|
}
|
|
|
|
private void Awake()
|
|
{
|
|
EnsureDefaultBindings();
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
if (!bindOnStart)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (mobileOnly && !Application.isMobilePlatform)
|
|
{
|
|
return;
|
|
}
|
|
|
|
ApplyBindings();
|
|
}
|
|
|
|
[ContextMenu("Apply Touch Region Bindings")]
|
|
public void ApplyBindings()
|
|
{
|
|
EnsureDefaultBindings();
|
|
|
|
for (int i = 0; i < regions.Length; i++)
|
|
{
|
|
BindRegion(regions[i], i);
|
|
}
|
|
}
|
|
|
|
private void EnsureDefaultBindings()
|
|
{
|
|
if (regions == null || regions.Length != 5)
|
|
{
|
|
regions = new RegionBinding[5];
|
|
}
|
|
|
|
for (int i = 0; i < regions.Length; i++)
|
|
{
|
|
if (regions[i] == null)
|
|
{
|
|
regions[i] = new RegionBinding();
|
|
}
|
|
|
|
regions[i].trackIndex = Mathf.Clamp(i, 0, 4);
|
|
}
|
|
}
|
|
|
|
private static void BindRegion(RegionBinding binding, int fallbackTrackIndex)
|
|
{
|
|
if (binding == null || binding.regionObject == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
int trackIndex = Mathf.Clamp(binding.trackIndex, 0, 4);
|
|
if (trackIndex != fallbackTrackIndex)
|
|
{
|
|
trackIndex = Mathf.Clamp(trackIndex, 0, 4);
|
|
}
|
|
|
|
Image image = binding.regionObject.GetComponent<Image>();
|
|
if (image == null)
|
|
{
|
|
image = binding.regionObject.gameObject.AddComponent<Image>();
|
|
}
|
|
|
|
image.color = binding.debugTint;
|
|
image.raycastTarget = true;
|
|
|
|
TrackTouchRegion touchRegion = binding.regionObject.GetComponent<TrackTouchRegion>();
|
|
if (touchRegion == null)
|
|
{
|
|
touchRegion = binding.regionObject.gameObject.AddComponent<TrackTouchRegion>();
|
|
}
|
|
|
|
touchRegion.trackIndex = trackIndex;
|
|
}
|
|
}
|