Tanoda
ClassTypeReference.cs
Go to the documentation of this file.
1// Copyright (c) Rotorz Limited. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root.
3
4using System;
5using UnityEngine;
6
7namespace TypeReferences {
8
12 [Serializable]
13 public sealed class ClassTypeReference : ISerializationCallbackReceiver {
14
15 public static string GetClassRef(Type type) {
16 return type != null
17 ? type.FullName + ", " + type.Assembly.GetName().Name
18 : "";
19 }
20
25 }
26
31 public ClassTypeReference(string assemblyQualifiedClassName) {
32 Type = !string.IsNullOrEmpty(assemblyQualifiedClassName)
33 ? Type.GetType(assemblyQualifiedClassName)
34 : null;
35 }
36
44 public ClassTypeReference(Type type) {
45 Type = type;
46 }
47
48 [SerializeField]
49 private string _classRef;
50
51 #region ISerializationCallbackReceiver Members
52
53 void ISerializationCallbackReceiver.OnAfterDeserialize() {
54 if (!string.IsNullOrEmpty(_classRef)) {
55 _type = System.Type.GetType(_classRef);
56
57 if (_type == null)
58 Debug.LogWarning(string.Format("'{0}' was referenced but class type was not found.", _classRef));
59 }
60 else {
61 _type = null;
62 }
63 }
64
65 void ISerializationCallbackReceiver.OnBeforeSerialize() {
66 }
67
68 #endregion
69
70 private Type _type;
71
78 public Type Type {
79 get { return _type; }
80 set {
81 if (value != null && !value.IsClass)
82 throw new ArgumentException(string.Format("'{0}' is not a class type.", value.FullName), "value");
83
84 _type = value;
85 _classRef = GetClassRef(value);
86 }
87 }
88
89 public static implicit operator string(ClassTypeReference typeReference) {
90 return typeReference._classRef;
91 }
92
93 public static implicit operator Type(ClassTypeReference typeReference) {
94 return typeReference.Type;
95 }
96
97 public static implicit operator ClassTypeReference(Type type) {
98 return new ClassTypeReference(type);
99 }
100
101 public override string ToString() {
102 return Type != null ? Type.FullName : "(None)";
103 }
104
105 }
106
107}
UnityEngine.Debug Debug
Definition: TanodaServer.cs:19
Reference to a class System.Type with support for Unity serialization.
ClassTypeReference(string assemblyQualifiedClassName)
Initializes a new instance of the ClassTypeReference class.
ClassTypeReference(Type type)
Initializes a new instance of the ClassTypeReference class.
ClassTypeReference()
Initializes a new instance of the ClassTypeReference class.
Type Type
Gets or sets type of class reference.
static string GetClassRef(Type type)