Terraria ModLoader  0.11.7.8
A mod to make and play Terraria mods
ContentInstance.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections;
3 using System.Collections.Concurrent;
4 using System.Collections.Generic;
5 using System.Linq;
6 
7 namespace Terraria.ModLoader
8 {
9  public static class ContentInstance
10  {
11  private class ContentEntry
12  {
13  private object instance;
14  private List<object> instances;
15  private Action<object, IEnumerable> staticUpdate;
16 
17  public void Register(object obj) {
18  lock (this) {
19  if (instances != null) {
20  instances.Add(obj);
21  }
22  else if (instance != null) {
23  instances = new List<object> { instance, obj };
24  instance = null;
25  }
26  else {
27  instance = obj;
28  }
29 
30  staticUpdate?.Invoke(instance, instances);
31  }
32  }
33 
34  public void Link(Action<object, IEnumerable> update) {
35  lock (this) {
36  staticUpdate = update;
37  update(instance, instances);
38  }
39  }
40 
41  public void Clear() {
42  lock (this) {
43  instance = null;
44  instances = null;
45  staticUpdate?.Invoke(instance, instances);
46  }
47  }
48  }
49 
50  private static ConcurrentDictionary<Type, ContentEntry> contentByType = new ConcurrentDictionary<Type, ContentEntry>();
51 
52  private static ContentEntry Factory(Type t) => new ContentEntry();
53 
54  internal static void Link(Type t, Action<object, IEnumerable> update) => contentByType.GetOrAdd(t, Factory).Link(update);
55 
56  public static void Register(object obj) => contentByType.GetOrAdd(obj.GetType(), Factory).Register(obj);
57 
58  internal static void Clear() {
59  foreach (var entry in contentByType)
60  entry.Value.Clear();
61  }
62  }
63 
64  public static class ContentInstance<T> where T : class
65  {
66  public static T Instance { get; private set; }
67  public static IReadOnlyList<T> Instances { get; private set; }
68 
69  static ContentInstance() {
70  ContentInstance.Link(typeof(T), Update);
71  }
72 
73  private static void Update(object instance, IEnumerable instances) {
74  Instance = (T)instance;
75  Instances = instances?.Cast<T>()?.ToArray();
76  }
77  }
78 }
object instance
List< object > instances
void Register(object obj)
static void Update(object instance, IEnumerable instances)
Action< object, IEnumerable > staticUpdate
void Link(Action< object, IEnumerable > update)
void Clear()