tModLoader v0.11.8.9
A mod to make and play Terraria mods
ContentInstance.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Concurrent;
4using System.Collections.Generic;
5using System.Linq;
6
7namespace 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
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;
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}
void Register(object obj)
List< object > instances
object instance
void Clear()
void Link(Action< object, IEnumerable > update)
Action< object, IEnumerable > staticUpdate
static void Update(object instance, IEnumerable instances)
static IReadOnlyList< T > Instances
static ConcurrentDictionary< Type, ContentEntry > contentByType
static ContentEntry Factory(Type t)
static void Register(object obj)