AR Design
UBC EML collab with UBC SALA - visualizing IoT data in AR
ValidateUnityObjectAttribute.cs
Go to the documentation of this file.
1 // Copyright (c) Microsoft Corporation. All rights reserved.
2 // Licensed under the MIT License. See LICENSE in the project root for license information.
3 
4 using System;
5 using System.Reflection;
6 #if UNITY_EDITOR
7 using UnityEditor;
8 #endif
9 
10 namespace HoloToolkit.Unity
11 {
12  // Validates object and displays an error or warning if validation fails
13  [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
14  public sealed class ValidateUnityObjectAttribute : Attribute
15  {
16  public enum ActionEnum
17  {
18  Success,
19  Warn,
20  Error,
21  HaltError,
22  }
23 
24  public ActionEnum FailAction { get; private set; }
25  public string MethodName { get; private set; }
26  public string MessageOnFail { get; private set; }
27 
28  public ValidateUnityObjectAttribute(string methodName, string messageOnError, ActionEnum failAction = ActionEnum.Warn)
29  {
30  MethodName = methodName;
31  MessageOnFail = messageOnError;
32  FailAction = failAction;
33  }
34 
35  public ActionEnum Validate(UnityEngine.Object target, System.Object source, out string messageOnFail)
36  {
37  if (source == null)
38  throw new NullReferenceException("Source cannot be null.");
39 
40  MethodInfo m = source.GetType().GetMethod(MethodName);
41  if (m == null)
42  throw new MissingMethodException("Method " + MethodName + " not found in type " + source.GetType().ToString());
43 
44  bool result = (bool)m.Invoke(source, new System.Object[] { target });
45 
46  if (result)
47  {
48  messageOnFail = string.Empty;
49  return ActionEnum.Success;
50  }
51 
52  messageOnFail = MessageOnFail;
53  return FailAction;
54  }
55  }
56 }
ValidateUnityObjectAttribute(string methodName, string messageOnError, ActionEnum failAction=ActionEnum.Warn)
ActionEnum Validate(UnityEngine.Object target, System.Object source, out string messageOnFail)