Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ZimM-LostPolygon/13c4a196f241072939d477998278948c to your computer and use it in GitHub Desktop.
Save ZimM-LostPolygon/13c4a196f241072939d477998278948c to your computer and use it in GitHub Desktop.
Editor script that adds System.Numerics assembly reference to Unity-generated C# projects
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using UnityEditor;
namespace Loom.Unity3d.Internal.Editor
{
/// <summary>
/// Adds System.Numerics assembly reference to Unity-generated C# projects.
/// </summary>
internal class AddSystemNumericsToCsProjectPostprocessor : AssetPostprocessor
{
public static void OnGeneratedCSProjectFiles()
{
string currentDirectory = Directory.GetCurrentDirectory();
string[] projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
foreach (string file in projectFiles)
{
AddSystemNumericsToProjectFile(file);
}
}
private static void AddSystemNumericsToProjectFile(string file)
{
XDocument project = XDocument.Load(file);
XElement projectRootElement = project.Root;
XNamespace xmlns = projectRootElement.Name.NamespaceName;
IEnumerable<XElement> existingReferences =
projectRootElement
.Elements(xmlns + "ItemGroup")
.Elements(xmlns + "Reference");
// Bail out of System.Numerics is already present
if (existingReferences.FirstOrDefault(reference => reference.Attribute("Include").Value == "System.Numerics") != null)
return;
// Get mscorlib.dll path for reference
XElement mscorlibReferenceElement =
projectRootElement
.Elements(xmlns + "ItemGroup")
.Elements(xmlns + "Reference")
.FirstOrDefault(a => a.Attribute("Include").Value == "mscorlib");
string mscorlibAssemblyPath =
mscorlibReferenceElement
.Element(xmlns + "HintPath")
.Value;
// Constuct and add System.Numerics reference
string systemNumericsAssemblyPath = Path.Combine(Path.GetDirectoryName(mscorlibAssemblyPath), "System.Numerics.dll");
XElement systemNumericsReferenceElement = new XElement(xmlns + "Reference");
systemNumericsReferenceElement.SetAttributeValue("Include", "System.Numerics");
XElement systemNumericsReferenceHintPathElement = new XElement(xmlns + "HintPath");
systemNumericsReferenceHintPathElement.Value = systemNumericsAssemblyPath;
systemNumericsReferenceElement.AddFirst(systemNumericsReferenceHintPathElement);
mscorlibReferenceElement.Parent.Add(systemNumericsReferenceElement);
project.Save(file);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment