module-project-validator/Editor/Validators/GameObject/GameObjectValidatorDuplicateComponents.cs

50 lines
No EOL
1.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Pool;
namespace Module.ProjectValidator.Editor
{
internal sealed class GameObjectValidatorDuplicateComponents : IGameObjectValidator
{
public void Validate(GameObject gameObject, List<ValidatorResult> results)
{
using var _ = ListPool<Component>.Get(out var list);
gameObject.GetComponents(list);
list.Sort((c0, c1) => c0.GetType().GetHashCode().CompareTo(c1.GetType().GetHashCode()));
if (list.Count == 0)
return;
var type = list[0].GetType();
var count = 1;
for (var i = 1; i < list.Count; i++)
{
var t = list[i].GetType();
if (type == t)
{
count++;
}
else
{
if (count > 1 && IsMultipleComponentsAllowed(type))
results.Add(ValidatorResult.Create(EValidatorSeverity.Warning, $"GameObject has duplicate '{type.Name}' ({count}) components"));
type = t;
count = 1;
}
}
if (count > 1 && IsMultipleComponentsAllowed(type))
results.Add(ValidatorResult.Create(EValidatorSeverity.Warning, $"GameObject has duplicate '{type.Name}' ({count}) components"));
}
private static bool IsMultipleComponentsAllowed(Type type)
{
return type.GetCustomAttribute<DisallowMultipleComponent>(true) == null;
}
}
}