Newer
Older
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
[RequireComponent(typeof(FactWrapper))]
public class FactFavorisation : MonoBehaviour, IPointerClickHandler
{
#region InspectorVariables
[Header("Prefabs")]
[SerializeField] private GameObject favoriteDisplayPrefab;
#endregion InspectorVariables
#region Static Variables
public static readonly UnityEvent<Fact, bool> ChangeFavoriteEvent = new();
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
private static readonly List<Fact> favorites = new();
#endregion Static Variables
#region Variables
private GameObject favoriteDisplay;
private Fact fact;
#endregion Variables
#region Properties
private bool isFavorite = false;
public bool IsFavorite
{
get { return isFavorite; }
set { ChangeFavoriteEvent.Invoke(fact, value); }
}
#endregion Properties
#region UnityMethods
public void OnPointerClick(PointerEventData eventData)
{
// TODO: add support for other input systems
if (eventData.button == PointerEventData.InputButton.Middle)
{
// write to property to invoke event
IsFavorite = !IsFavorite;
// update favorites list
if (isFavorite)
favorites.Add(fact);
else
favorites.Remove(fact);
}
}
private void Start()
{
fact = transform.GetComponent<FactWrapper>().fact;
ChangeFavoriteEvent.AddListener(OnFavoriteChange);
// if there already was a favoriteDisplayPrefab child (e.g. due to cloning) remove it
gameObject.ForAllChildren(child => {
if (child.name.StartsWith(favoriteDisplayPrefab.name))
Destroy(child);
});
// instantiate new favoriteDisplay
favoriteDisplay = Instantiate(favoriteDisplayPrefab, transform);
// check if fact is currenty a favorite
isFavorite = favorites.Contains(fact);
UpdateDisplay();
}
#endregion UnityMethods
#region Implementation
private void OnFavoriteChange(Fact changedFact, bool isFavorite)
{
if (fact == changedFact)
{
this.isFavorite = isFavorite;
UpdateDisplay();
}
}
private void UpdateDisplay()
{
favoriteDisplay.SetActive(isFavorite);
}
#endregion Implementation
}