How to solve `missing reference error` with unit-test in Unity? - c#

I try to make a simple nunit test within Unity, but get missing reference error when i try to reference a MyScript
Project setup:
├── Assets
├── Scenes
├── Scripts
│ └── MyScript.cs
│ └── NewAssembly.asmdef -> see below "what i tried"
├── Tests
│ ├── MyScriptTest.cs
│ └── Tests.asmdef
Tests.asdmdef (created by Unity)
{
"name": "Tests",
"rootNamespace": "",
"references": [
"UnityEngine.TestRunner",
"UnityEditor.TestRunner"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [],
"noEngineReferences": false
}
MyScriptTest.cs:
using NUnit.Framework;
public class MyScriptTest
{
[Test]
public void SomeTest()
{
var obj = new MyScript(); // Error CS0246 The type or namespace name 'MyScript' could not be found (are you missing a using directive or an assembly reference?)
}
}
MyScript.cs
using UnityEngine;
using TMPro; // see below "What i tried"
public class MyScript : MonoBehaviour {}
Unity: 2030.3.37f1
Visual Studio: 2019 (Version 16.11.20)
What i tried
I tried to solve the problem with how-to-set-up-unit-tests-in-unity-and-fix-missing-assembly-reference-error by creating a Assemply Definition in Scripts/. This solves the error in MyScriptTest.cs, but then i got tons of other errors in my (previously working) scripts like Assets\Scripts\MyScript.cs(2,7): error CS0246: The type or namespace name 'TMPro' could not be found (are you missing a using directive or an assembly reference?)
Any help is welcome! I can't believe this is so complicated....
Update:
Above was just a small example of the problem. I have around 46 issues like this in my project (many of the link to external libraries or own classes which i can't find the suitable reference by its name), so having an assembly reference for every single using in my project just to do unit test work is not acceptable. Is this really the only way to do unit test work in Unity?

in the NewAssembly - which the MyScript belongs to - reference the Unity.TextMeshPro assembly (and any others that are required) as dependency (= "references")

Related

Build.cs not working even after being restores to it's previous version

I'm trying to compile a project I'm working on and this error mesages pops out:
Invalidating makefile for SpaceShooterEditor (SpaceShooter.Build.cs modified)
While compiling E:\ue projects\SpaceShooter\Intermediate\Build\BuildRules\SpaceShooterModuleRules.dll:
e:\ue projects\SpaceShooter\Source\SpaceShooter\SpaceShooter.Build.cs(3,29) : error CS0246: The type or namespace name 'ModuleRules' could not be found (are you missing a using directive or an assembly reference?)
e:\ue projects\SpaceShooter\Source\SpaceShooter\SpaceShooter.Build.cs(5,25) : error CS0246: The type or namespace name 'ReadOnlyTargetRules' could not be found (are you missing a using directive or an assembly reference?)
ERROR: Unable to compile source files.
Any idea why this might happen? Last night i was trying to code a widget, modified the build.cs, then replaced the modified version (which chrashed the game) with a build.cs that worked previously, and still nothing? Is there any hope to make it work or should i start over? Moreover, how can this be avoided?
I already did the restarts and refreshes. I went to even delete the binaries and some cashed files and it didn't work.
Below you'll find the content of the Build.cs:
public class SpaceShooter : ModuleRules
{
public SpaceShooter(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
When i try to input specify the using UnrealBuildTool;, Visual Studio, for some reason, deletes it when i hit compile or save.
After some digging, i found out that wrapping the content in a namespace UnrealBuidTool.Rules{} solves this. In the end, the build file looks like this:
namespace UnrealBuildTool.Rules
{
public class SpaceShooter : ModuleRules
{
public SpaceShooter(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" });
PrivateDependencyModuleNames.AddRange(new string[] { });
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
}
}
}
As you do not share what is included in your Build.cs file I will just explain what the error is and how you could fix it. The error basically says that it couldn't compile the Build.cs file based on the lines 29 and 25, and that the types that are used there called 'ModuleRules' and 'ReadOnlyTargetRules' could not be found in any of the namespaces that were included by the using statements at the top of Build.cs. These types are both stored in the UnrealBuildTool namespace and can thus be included in your file by typing:
using UnrealBuildTool;
This however seems like a trivial solution to your problem, but as you do not share a lot of info this is the best solution I can give you for now.

The type or namespace name 'NativeShare' could not be found (are you missing a using directive or an assembly reference?)

i'm using native share to share unity game. But i'm facing this error. How to resolve this?
Directories
using UnityEngine;
using UnityEngine.UI;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.SavedGame;
using System.IO;
using System.Collections;
Native Share Code
private IEnumerator TakeScreenshotAndShare()
{
yield return new WaitForEndOfFrame();
Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
ss.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
ss.Apply();
string filePath = Path.Combine(Application.temporaryCachePath, "shared img.png");
File.WriteAllBytes(filePath, ss.EncodeToPNG());
// To avoid memory leaks
Destroy(ss);
new NativeShare().AddFile(filePath).SetSubject("Control The Pandemic").SetText("I found this game most attractive!").Share();
}
public void ShareGame()
{
StartCoroutine(TakeScreenshotAndShare());
}
ERROR
CS0246: The type or namespace name 'NativeShare' could not be found (are you missing a using directive or an assembly reference?)
You probably need to add using NativeShare to the top of your script.
If that's not the issue and if NativeShare has its own assembly definition file, those can sometimes freak out for no reason in Unity. In that case close everything (unity visual studio etc.), delete the unity temporary folders (Libray, obj in root of your project) and open the project again.
Sol 1 - Try closing Unity, Unity HUB, VS Code and reopening it.
(Alternate) Sol 2 - After closing VS Code, try Unity -> Preferences -> External Tools -> Regenerate project files.

Unable to reference a namespace in another assembly when it partially matches one in the current assembly

I have a project of namespace SpaceCats.Planet.Types that has a class called MajorTomCat.cs
My test project namespace is Test.Fiddlesticks
In my test project, there is a namespace Test.Fiddlesticks.SpaceCats which is generated automatically from a WCF service reference
When I do MajorTomCat cat = new MajorTomCat(), it says it cannot find MajorTomCat.
I try to put it explicitly:
SpaceCats.Planet.Types.MajorTomCat cat;
But it still can't find it. Hovering over it, it says
The type or namespace Planet does not exist in the namespace Test.Fiddlesticks.SpaceCats.
It appears to be looking in the wrong SpaceCats namespace.
I can't figure out how to force it to look in the root.
Any ideas?

How do I find all namespaces in my Visual Studio solution?

I ask this question because I'm getting a compilation error in my solution:
'GiftCard' is a 'namespace' but is used like a 'type'
I tried adding a using directive like:
using GiftCard.Data.Entity;
which is the correct namespace where GiftCard is found, but the error does not go away. When I add the fully qualified name in my code, i.e. GiftCard.Data.Entity.GiftCard
...then the error goes away, and code compiles.
But I'm wondering why the using directive does not work. I don't want to clutter my code with the fully qualified name every time I need to use the type. Somehow the error message is saying that I have GiftCard defined as a namespace somewhere. So how can I find all the namespaces in my solution so that I know where it is defined because I need to either remove or rename the GiftCard namespace.
Your question is not quite related to your problem.
The Problem
The Framework Design Guidelines says Do not use the same name for a namespace and a type in that namespace.
For example, do not use Debug as a namespace name and then also
provide a class named Debug in the same namespace. Several compilers
require such types to be fully qualified.
That is:
namespace Debug
{
public class Debug{ … }
}
OR
namespace MyContainers.List
{
public class List { … }
}
Why is this badness? Do not name a class the same as its namespace
Answer for the Question
View -> Object Browser (Shortcut : Ctrl+Alt+J)
Use Powershell:
dir -r -filter *.cs | Select-String -pattern "^using" | Select-Object -expand Line -unique | Format-List -property Line
Run the above in a solution's root directory and the output will be something like:
using NUnit.Framework;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
For more info take a look at this page.

Visual Studio adding prefix to stated namespace

I'm getting a few:
'The type or namespace 'blah' does not exist in 'A.B.C' (are you missing an assembly reference?)
The code looks like:
namespace A
{
using B.C;
public class Blah()
{
//...
}
}
A and B are both assemblies that are included in the solution. Both use .NET 4.0. Assembly B does in fact have a namespace C. Assembly B is included as a reference in assembly A.
Why is it looking for A.B.C when the reference is B.C?
The problem was a typo in a different file than the ones with errors.
In another file I had:
namespace A.B.C
{
//...
}
I must have done an accidental Ctrl-P at some point?
The steps I took to find the offending file:
Open up the most recent file that I had changed
Examine the namespace
Repeat with the next most recent

Categories