The type or namespace name could not be found unity как исправить

I am setting up a new scriptable object in Unity 5 and when I am trying to set up a reference to it an error shows up :'The type or namespace name 'ES' could not be found (are you missing a using

I am setting up a new scriptable object in Unity 5 and when I am trying to set up a reference to it an error shows up :’The type or namespace name ‘ES’ could not be found (are you missing a using directive or an assembly reference?’

the scriptable object script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "new ES", menuName = "ES")]

public class LAMP: ScriptableObject {
    public int groupNum;

    void Start() {

        groupNum = 1;

    }

}

the reference in monobehavior script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bout: MonoBehaviour {

    public ES et;

    // Use this for initialization
    void Start() {

    }

    // Update is called once per frame
    void Update() {

    }
}

Lance U. Matthews's user avatar

asked Dec 24, 2018 at 15:43

Mwiak 's user avatar

It is a name space error ,if you are using a collision variable you face this error.

Using My.Players.namespace;

answered Oct 23, 2021 at 17:22

AKASH PATIL's user avatar

1

Just had this error and this is the top SO post about it, so I’ll post my fix here:

We introduced unit tests, which require the .asmdef for each «group» of related scripts. In this particular instance for us, the original developer had the .asmdef file for scripts that were contained in an AutoGenerated folder (ROS messages) that was set to be ignored by Git.

He pushed the code, Git ignored the .asmdef file for the AutoGenerated files, and then because we were using .asmdef files and that folder wasn’t included on MY box, my Unity «couldn’t find» the files there.

This could be your problem, too, but 99 times out of 100 you get this error because you’ve misspelled the class name — capitalization matters! In OP’s case specifically the actual class is LAMP even though it’s called ES in the AssetMenu. Instead of public ES et; OP should have had public LAMP et; and then it would work.

answered Nov 10, 2021 at 19:57

Chuck's user avatar

ChuckChuck

1,8531 gold badge17 silver badges23 bronze badges

In your file Bout.cs you are trying to create the variable ‘et’ of type ES but the type ES doesn’t exist, you may want to create a LAMP?

public class Bout: MonoBehaviour {
public LAMP et;

// Use this for initialization
void Start() {

Creating a scriptable object file named ES (fileName = «new ES») doesn’t mean it’s type is ES, it takes the type of the class i.e LAMP

answered May 28, 2022 at 19:03

Yanis b.'s user avatar

I have encountered the same error while trying to add script component to the gameobject on runtime. Fixed it by following this format:

GameObject.AddComponent(typeof(namespace.className));

RBT's user avatar

RBT

23.1k21 gold badges155 silver badges232 bronze badges

answered Jun 1, 2022 at 3:53

Issatay Sissemali's user avatar

The meaning of The type or namespace name 'xxxx' could not be found is because you are trying to use a class that do not exist or you are not using the namespace where that class is.

The problem that you have is that you are trying to use something that do not exists.

You are trying to create a scriptable object named ES, but it’s totally different to create a class named ES.

If you create the class ES you will see that the error goes away.

answered Dec 24, 2018 at 15:47

Martin Gonzalez's user avatar

Egor12

0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

1

18.01.2021, 14:23. Показов 40563. Ответов 16

Метки unity (Все метки)


Здраствуйте может кто то знает. Я создаю игру на движке unity и у меня ошибка CS0246 можете пожалуйста подсказать как её убрать?

AssetsSpawner.cs(8,12): error CS0246: The type or namespace name ‘Gameobject’ could not be found (are you missing a using directive or an assembly reference?)

вот такая ошибка.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
 
public class Spawner : MonoBehaviour
{
    public Gameobject[] Blocklines;
 
    public float speed;
    public float speedIncrease;
 
    // Update is called once per frame
    private void Update()
    {
        speed += spawner.speedIncrease * Time.deltaTime;
    }
 
    public void SpawnWave()
    {
        int rand = Random.Range(0, Blocklines.Length);
        Instantiate(Blocklines[rand], transform.postition, Quaternion.identity);
 
    }
 
 
 
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

18.01.2021, 14:23

Ответы с готовыми решениями:

Как убрать ошибку
Начал заниматься по книге Васильева А.Н. Программирование для начинающих на С#, первая программа…

Как убрать ошибку?
Привет всем. Загрузил сайт на opencart на хостинг. все работает. Но если пытаюсь зайти в админку…

Как убрать ошибку?
"функция ord с параметрами указанных типов не найдена"

Программа переводит два заданных числа из…

ошибка CS0246 в проекте как исправить?
При компиляции вылетает ошибка CS0246, как это исправить?

16

109 / 81 / 37

Регистрация: 13.01.2016

Сообщений: 395

18.01.2021, 16:50

2

Строка 8. GameObject. Вторая часть типа тоже с большой буквы



1



0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

18.01.2021, 16:58

 [ТС]

3

Огромное спасибо но теперь ошибка
AssetsSpawner.cs(15,18): error CS0103: The name ‘spawner’ does not exist in the current context



0



74 / 53 / 24

Регистрация: 19.10.2012

Сообщений: 212

18.01.2021, 18:10

4

speed += spawner.speedIncrease * Time.deltaTime; Убери spawner

speed += speedIncrease * Time.deltaTime;

Добавлено через 28 секунд
Используй IDE



1



250 / 186 / 68

Регистрация: 04.03.2019

Сообщений: 1,010

18.01.2021, 18:16

5

Цитата
Сообщение от Egor12
Посмотреть сообщение

spawner.speedIncreas

Spawner с большой буквы.
а еще лучше убрать как пишут выше



1



Egor12

0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

18.01.2021, 21:29

 [ТС]

6

Спасибо большое, но у меня появилась ещё одна ошибка

AssetsDownMover.cs(24,23): error CS1061: ‘Transform’ does not contain a definition for ‘postition’ and no accessible extension method ‘postition’ accepting a first argument of type ‘Transform’ could be found (are you missing a using directive or an assembly reference?)

что то я так понимаю с ‘Transform’ не так.

буду очень благодарен за помощь.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Spawner : MonoBehaviour
{
    public GameObject[] Blocklines;
 
    public float speed;
    public float speedIncrease;
 
    // Update is called once per frame
    private void Update()
    {
        speed += speedIncrease * Time.deltaTime;
    }
 
    public void SpawnWave()
    {
        int rand = Random.Range(0, Blocklines.Length);
        Instantiate(Blocklines[rand], transform.postition, Quaternion.identity);
 
    }
 
 
 
 
}



0



74 / 53 / 24

Регистрация: 19.10.2012

Сообщений: 212

18.01.2021, 21:40

7

Во первых у тебя с верху написана ошибка. ее в переводчик.
Потом повторюсь используй IDE любой и настрой под Unity

Instantiate(Blocklines[rand], transform.postition, Quaternion.identity);
position

все красное ошибки твоего кода.
А так ты тут поселишься.

Миниатюры

Как убрать ошибку CS0246?
 



0



0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

18.01.2021, 22:02

 [ТС]

8

Спасибо мне 12 только учусь поэтому у меня столько ошибок )

2 первые ошибки я уже исправил. А там где postition его просто удалить ?

Я не настраивал visual studio под unity потому что не знал что это нужно делать, и не знаю как.



0



74 / 53 / 24

Регистрация: 19.10.2012

Сообщений: 212

18.01.2021, 22:26

9

Ну Youtube в помощь. Я тоже начал примерно в этом возрасте. Очень давно.



0



0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

18.01.2021, 22:51

 [ТС]

10

Спасибо понял. Так всё таки postition убрать из скрипта ?



0



74 / 53 / 24

Регистрация: 19.10.2012

Сообщений: 212

18.01.2021, 23:41

11

Лучший ответ Сообщение было отмечено Egor12 как решение

Решение

Цитата
Сообщение от Egor12
Посмотреть сообщение

Так всё таки postition убрать из скрипта ?

написано с ошибкой просто.
Правильно position а не posTition

Добавлено через 4 минуты
Выучи основы c# это не так много. Просто Азы. Потом основы Unity. Это неделя по вечерам. Может ты и не будешь далеко Гуру, но в таких мелочах не ошибешься. А юзать Unity будет интереснее. Мб и поймешь куда поступать. ) Удачи.



0



0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

19.01.2021, 10:59

 [ТС]

12

Хорошо огромное спасибо ))



0



0 / 0 / 0

Регистрация: 18.01.2021

Сообщений: 20

20.01.2021, 14:28

 [ТС]

13

Почему-то speedIncrease работает то есть скорость становиться больше со временем, а Spawner не работает он не спавнит BlockLines.



0



Eli_To4Ka

0 / 0 / 0

Регистрация: 23.11.2021

Сообщений: 1

23.11.2021, 12:37

14

Ночью сидел писал код, по примеру ютубера… у него все работает у меня нет… cs0246 ошибку выбивает.
Может ктото мне тыкнуть пальцем, где мои сонные глаза чегото не увидели?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
 
public class AchMenu : MonoBehaviour
{
    public int total_money;
    [SerializeField] Button firstAch;
    [SerializeFiled] bool isFirst;
    void Start()
    {
        total_money = PlayerPrefs.GetInt("total_money");
        isFirst = PlayerPrefs.GetInt("isFirst") == 1 ? true : false;
        if (total_money >= 10 && !isFirst)
        {
            firstAch.interactactable = true;
        }
        else
        {
            firstAch.interactactable = false;
        }
    }
 
    public void GetFirst()
    {
        int money = PlayerPrefs.GetInt("money");
        money += 10;
        PlayerPrefs.SetInt("money", money);
        isFirst = true;
        PlayerPrefs.SetInt("isFirst", isFirst ? 1 : 0);
    }
 
    public void ToMenu()
    {
        SceneManager.LoadScene(0);
    }
 
    void Update()
    {
 
    }
}



0



538 / 350 / 196

Регистрация: 18.10.2019

Сообщений: 1,164

23.11.2021, 14:13

15

Eli_To4Ka, interactactable. Правильно — interactable.
Строки 18 и 22.



0



Sovock

0 / 0 / 0

Регистрация: 06.02.2022

Сообщений: 1

06.02.2022, 16:13

16

Делал год из интеренета, всё сделал как на ролике, но появляется ошибка:

(AssetsscriptsMovePlayer.cs(49,20): error CS1061: ‘Rigidbody’ does not contain a definition for ‘AddForse’ and no accessible extension method ‘AddForse’ accepting a first argument of type ‘Rigidbody’ could be found (are you missing a using directive or an assembly reference?)

вот код:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
 
public class MovePlayer : MonoBehaviour
{
    [Header("Скорость передвижения")]
    public float speed = 7f;
 
    [Header("Сила прыжка")]
    public float jumpPower = 200f;
 
    [Header("Земля под ногами???")]
    public bool ground;
 
    public Rigidbody rb;
 
 
 
    private void Update()
    {
        GetInput();
    }
 
    void GetInput()
    {
        if (Input.GetKey(KeyCode.W))
        {
            transform.localPosition += transform.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.localPosition += -transform.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.A))
        {
            transform.localPosition += -transform.right * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.localPosition += transform.right * speed * Time.deltaTime;
        }
 
        if(Input.GetKeyDown(KeyCode.Space))
        {
            if(ground == true)
            {
                rb.AddForse(transform.up * jumpPower);
            }
        }
    }
 
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag == "Ground")
        {
            ground = true;
        }    
    }
 
    private void OnCollisionExit(Collision collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            ground = false;
        }
    }
}



0



538 / 350 / 196

Регистрация: 18.10.2019

Сообщений: 1,164

06.02.2022, 16:18

17

Sovock, метод правильно называется AddForce



0



Recommended

  • 1. Download ASR Pro
  • 2. Follow the on-screen instructions to run a scan
  • 3. Restart your computer and wait for it to finish running the scan, then follow the on-screen instructions again to remove any viruses found by scanning your computer with ASR Pro
  • Speed up your PC today with this easy-to-use download.

    You may receive an error message indicating Visual Studio error cs0246. There are several ways to solve this problem, and we will deal with it shortly. g.Unity error: CS0246: Could not find type or namespace name ‘image’ (are you missing a take directive or an assembly reference?) “

    Error CS0246: The type or namespace name ‘________’ could not be found. Do you still have any guidance on using personal directories? The root cause. This error occurs when the namespace you are trying to use does not exist.

    Error CS0246: The type or namespace name ‘________’ could not be found. Don’t have a using directive from your assembly references? The root cause. This error always occurs when the namespace you are trying to use does not exist.

    error cs0246 visual studio

    Typeor namespace alias ‘type / namespace’ not found (is there a public directive or strong assembly reference missing?)

    Recommended

    Is your PC running slow? Do you have problems starting up Windows? Don’t despair! ASR Pro is the solution for you. This powerful and easy-to-use tool will diagnose and repair your PC, increasing system performance, optimizing memory, and improving security in the process. So don’t wait — download ASR Pro today!

  • 1. Download ASR Pro
  • 2. Follow the on-screen instructions to run a scan
  • 3. Restart your computer and wait for it to finish running the scan, then follow the on-screen instructions again to remove any viruses found by scanning your computer with ASR Pro
  • The type or namespace in which it is used in a program has not previously been found. Perhaps you have defined a reference ( references ) to the assembly containing the type, or you probably did not add the required using statement. Or it may have a congregation problem that people are trying to link to.

    • There are two answers to this error. The first is when you need to correct the namespace name to match the existing one. The goal is to rebuild the newly created custom namespace.

      Did you misspell a name like “also”? Without the correct name, the user compiler cannot find a definition for the type or namespace. This happens all the time because the case used for the type name is incorrect. For example, Ds; dataset creates CS0246 because the s in the dataset must be uppercase.


    • If this particular error is manufacturer namespace, add a reference ( References ) directly to the assembly containing its namespace. Names? For example, your code could be using the Accessibility directive . However, if your project is not referenced In its assembly Accessibility.dll, error CS0246 will be declared. For information see Boards a in Project

    • If an error can occur with the type name, did you include the correct using statement, or, if that failed, did you just fully define the name associated with the type? See the following document: DataSet ds . To use the DataSet part, you need two things. First, you need a reference to this assembly, which contains a definition that is of type DataSet . Second, you need to use with one directive for the entire namespace that contains the DataSet . Since DataSet is in each of our System.Data namespaces, you should generally follow the instructions at the beginning of your preferred code for argumentation: using System.Data .

      How do I fix error CS0103?

      CS0103 is called when you use an address for a variable or method that does not exist in the situation in which you are using it. To fix CS0103, you need to fix any variable or system name from which it is declared or possibly referenced.

      The using directive is definitely not required. However, if you skip a statement, you must fully meet the criteria for a DataSet if you do reference it. Fully qualified means that whenever you give time to a type in your codeThat is, most people specify both the type and the namespace. If you omit the using directive from the previous example, you would compose System.Data.DataSet ds to get ds instead of <. to declare the code> DataSet ds .

    • Have you used an appropriate variable to determine where the type was expected? For example, if you use the Type object, preferably the actual type, in the is statement, you will encounter error CS0246.

    • error cs0246 visual studio

      Did you mean an installation built for a version of the platform that is larger than the target program? Or maybe you mentioned a project targeting a higher version of the framework than what you see in the target program structure? For example, you are working on a distribution targeting the .NET Framework 4.6.1 and a project-specific use case targeting the .NET Framework 4.7.1. Then you will get error CS0246.

    • How do I fix namespace errors?

      Select View >> Solution Explorer.Right click on your project and select Properties.On the Project Properties tab, click Compile.Select Advanced Compilation Options.Choose . NET Framework 4 from the Target Framework dropdown.

      Have you used the alias information without specifying the full legal name? The using alias directive typically uses the using directives in a source file to resolve forms. In the next exampleCS0246 is not generated because the type List is not fully defined. The using directive in System.Collections.Generic does not prevent the error.

        with System.Collections.Generic;// The following announcement has been moved to CS0246.using myAliasName = List ;// Fill in the spec list to avoid errors.using myAliasName2 = System.Collections.Generic.List ; 

      If you get this type of error in code you've tried, first check Solution Explorer for missing or dangerous links. Do I need to reinstall the NuGet package? For more information on improving the search for system credentials, see Allowing file credentials in Team Build . When all links seem to be covered, check your source code check time to see what changed in your .csproj file and / or city source file.

      If you haven't yet evaluated the link, use Object Explorer to inspect the assembly that should contain this process namespace and see if this namespace might exist. When using Object Browser to verify that this assembly withtakes over the namespace, try removing the using information for the namespace and explore other language factions. The main problem can arise especially with a different type of different assembly.

    The following example creates CS0246 a because the required using directive is indeed missing.

      // CS0246.cs// with System.Diagnostics;  public class maclass      // The next line calls CS0246. To fix the error, uncomment it.   // type of namespace using directive to get this attribute,   // system diagnostics.   [Conditional ("A")]   invalid public test ()                 Static Font Empty Main ()              

    Why am I getting error CS0246 the type or namespace name could not be found?

    You may have forgotten to reference this assembly containing the type, or the clients may not have added the required directive. Or there may be a dilemma with the assembly you are trying to reference. Without the correct name, these compilers cannot find the human type or namespace definition.

    The following example calls CS0246 because the Type form object was used where the actual form was expected.

    How do I fix namespace errors?

    Select View >> Solution Explorer.Right click on your project and select Properties.On the Project Properties tab, select Compile.Select Advanced Compilation Options.Choose . NET Framework 3 from the Target Framework dropdown.

      // CS0246b.csSystem use;  Example class class     generic boolean support (object o, type t)              // The used string calls CS0246. You must wear one       // a serious type such as ExampleClass, String, or Type.        should (oh there are t)                      returns true;                  return at is incorrect;          Class program      Public static void Main ()              ExampleClass myC corresponds to the new ExampleClass ();        myC.supports (myC, myC.GetType ());         
    • 4 reading cycles

    Speed up your PC today with this easy-to-use download.

    Are you missing a using directive or an assembly reference Visual Studio 2019?

    Open the current project in Solution Explorer.Right-click the Links folder and select Add Link.Find and select the assembly that might match your error message.Click OK to add it to your project.

    How do I fix namespace errors?

    Select View >> Solution Explorer.Right click on your project and select Properties.Select Compile from the navigation bar of the project properties.Select Advanced Compilation Options.Choose . NET Framework 4 from the Target Framework dropdown.

    How do you fix Are you missing a using directive or an assembly reference?

    Open the project in Solution Explorer.Right-click the Links folder and select Add Link.Find and select the assembly that matches your error message, also known as a class.Click OK to add them to your project.

    How do I fix error cs0234?

    If you should see this error after migrating code from one development machine to another, make sure the company has the correct part numbers on the new machine and that the assembly solutions are the same as on the old machine.

    Blad Cs0246 Visual Studio
    Erreur Cs0246 Studio Visuel
    Fout Cs0246 Visuele Studio
    Error Cs0246 Visual Studio
    Fel Cs0246 Visual Studio
    Fehler Cs0246 Visual Studio
    Erro Cs0246 Visual Studio
    Errore Cs0246 Studio Visivo
    오류 Cs0246 비주얼 스튜디오
    Oshibka Cs0246 Visual Studio

    Related posts:

    How To Fix A Debug Stored Procedure Error In Visual Studio

    Tips To Resolve FTP Error 126 Remote Rmdir Error

    Tips To Resolve Alaska Airlines Error Code 1580

    Troubleshoot And Resolve Wii Error 003 Solution Detected By Unauthorized Device

    Keywords: Unity, Solution for common issues

    failed to open source file: ‘Packages/com.unity.render-pipelines.xxx’

    Error at compiling assets:

    Shader error in 'XXX': failed to open source file: 'Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl' at line 72 (on d3d11)
    

    Reason:
    Render pipelines were missed in project, e.g. you created a project using 3D template.

    Solution:
    Create a project using LWRP template or High Definition RP template, these two templates provided new render pipelines.

    Reference:
    [LWRP] UPGRADING LWRP PACKAGE TO 7.0.0 BREAKS FORWARDRENDERDATA ASSET IN RESOURCE FILES
    https://issuetracker.unity3d.com/issues/lwrp-upgrading-lwrp-package-to-7-dot-0-0-breaks-forwardrenderdata-asset-in-resource-files

    Assets go pink

    Issue:
    Assets in scene go pink (purple).

    Reason:
    1, Materias and shaders of assets were missed.
    2, Materias and shaders of assets using old render pipeline which not support in new verson.

    Solution:
    Retarget materias and shaders in meshes or update materials and shaders.

    Reference:
    everything became pink
    https://answers.unity.com/questions/168624/everything-became-pink.html

    Error CS0246: The type or namespace name ‘float2’ could not be found

    Error at building project

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

    Caused by:
    Missing requisite package.

    Solution:
    Install Mathematics: Windows -> Package Manager -> Select Mathematics and click Install.

    An assembly with the same simple name ‘SyntaxTree.VisualStudio.Unity.Bridge’ has already been importe

    Error log in editor console:

    error CS1704: An assembly with the same simple name 'SyntaxTree.VisualStudio.Unity.Bridge' has already been imported. Try removing one of the references (e.g. 'D:Program_Filesx86Microsoft Visual Studio Tools for Unity16.0EditorSyntaxTree.VisualStudio.Unity.Bridge.dll') or sign them to enable side-by-side.
    

    Error log on compiling project in Visual Studio:

    error CS0234: The type or namespace name 'UI' does not exist in the namespace 'UnityEngine'
    

    Solution:

    1. Close Editor and Visual Studio.
    2. Remove file C:Program Files(x86)Microsoft Visual Studio Tools for Unity16.0EditorSyntaxTree.VisualStudio.Unity.Bridge.dll.
    3. Remove files .sln and .csproj and remove directories Library and obj.
    4. Reimport project and open Editor and Visual Studio.

    It is not a lack of love, but a lack of friendship that makes unhappy marriages. ― Friedrich Nietzsche, Twilight of the Idols

    FIX FOR ALL UNITY VERSIONS
    So, this is how I fixed this problem after multiple failed attempts and bad advice from a countless number of people who think they know how computers work.
    This issue is caused by, loading in old projects, altering visual studio, switching from computer, using different Unity versions, updating Unity, bad file management and a few other causes which I couldn’t care to put down here.
    Non of the steps below are extreme, they are all but necessary.So lets fix your project mate, so you don’t have to sweat like I did, which I did a lot ahaha =P
    — Making sure your Unity software is closed during the fix:

    1. DO NOT START UP UNITY

    2. MAKE SURE UNITY HUB AND OTHER UNITY PROGRAMS ARE CLOSED (Via both taskbar icon & task manager, Unity will resolve the packages if it is opened, so make sure it is closed)
      — Deleting the first problem:

    3. Go to C:UsersUSERNAMEAppDataLocalUnitycachepackagespackages.unity.com

    4. Delete ALL the folders inside «packages.unity.com»
      — Deleting the second problem:

    5. Go to your project folder, so your game folder, in my case it is saved in the USER folder which is named after your computer’s username, so for me it is «C:UsersUSERNAMEYOUR PROJECTLibraryPackageCache»

    6. Delete ALL the folders inside the «PackageCache»
      — Deleting the third and final problem:

    7. Go to C:UsersUSERNAMEYOUR PROJECTPackages

    8. Delete BOTH manifest.json & packages-lock.json (These hold the packages list and versions, packages with versions will be resolved/updated when unity is open or launched)

    9. Start up your Unity editor and… hopefully your console will be empty.
      * Note that the USERNAME is the directory paths needs to be replaced with YOUR computer username
      ** YOUR PROJECT is a place holder for the name of your project
      *** The appdata directory can easily be found by entering %appdata% in the windows search bar on the bottom left of your display
      I want to state in these last lines how bad Unity is designed and how careless the developers are towards their consumers, this is a terrible service to subscribe to, liability wise.This bug bothers an enormous majority of their user base and is completely ignored.
      For a company that tries to make game making easy, they are making it awfully hard on people who are trying to create their dreams with THEIR software.

    Unity3D error CS0246 - howto fix tutorial



    Trabla Description:

    1. Simple project


    2. Script «MyBuildScript.cs» to add custom menu to Unity3d Editor
    — compile project for Androdi or iOS

    Located in Assets folder

    Unity3D error CS0246 - howto fix tutorial 1

    3. Source code of  «MyBuildScript.cs» script:

    using UnityEngine;

    using System.Collections;

    using System.Collections.Generic;

    using UnityEditor;

    class MyBuildScript

    {

    static string[] SCENES = FindEnabledEditorScenes();

    static string APP_NAME = «Demo»;

    static string TARGET_DIR = «C:\Users\Public\Documents\Unity Projects\demo-buildScript»;

    [MenuItem(«Custom/CI/Build Mac OS X»)]  // Creates menu item in unity editor

    public static void PerformMacOSXBuild()

    {

    string target_dir = APP_NAME + «.app»;

    GenericBuild(SCENES, TARGET_DIR + «/» + target_dir, BuildTarget.StandaloneOSXIntel, BuildOptions.None);

    }

    [MenuItem(«Custom/CI/Build Android»)]   // Creates menu item in unity editor

    public static void PerformAndroidBuild()

    {

    string target_dir = APP_NAME + «.apk»;

    GenericBuild(SCENES, TARGET_DIR + «/» + target_dir, BuildTarget.Android, BuildOptions.None);

    }

    private static string[] FindEnabledEditorScenes()

    {

    List<string> EditorScenes = new List<string>();

    foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)

    {

    if (!scene.enabled) continue;

    EditorScenes.Add(scene.path);

    }

    return EditorScenes.ToArray();

    }

    static void GenericBuild(string[] scenes, string target_dir, BuildTarget build_target, BuildOptions build_options)

    {

    EditorUserBuildSettings.SwitchActiveBuildTarget(build_target);

    string res = BuildPipeline.BuildPlayer(scenes, target_dir, build_target, build_options);

    if (res.Length > 0)

    {

    throw new System.Exception(«BuildPlayer failure: » + res);

    }

    }

    }

    Unity3D error CS0246 - howto fix tutorial 2

    4. Try to run build script from Editor  — menu «Custom» -> «CI» -> «Build Android»

    5. Exception:

    Assets/MyBuildScript.cs(4,7): error CS0246: The type or namespace name `UnityEditor’ could not be found. Are you missing a using directive or an assembly reference?

    Unity3D error CS0246 - howto fix tutorial 3



    Solving:


    1. Create folder «Editor» in «Assets» folder

    Unity3D error CS0246 - howto fix tutorial 4



    2. Move script «MyBuildScript.cs» to «Assets» -> «Editor» folder

    Unity3D error CS0246 - howto fix tutorial 5

    All scripts with using UnityEditor; should be placed in «Assets» -> «Editor» folder

    Понравилась статья? Поделить с друзьями:
  • The type attribute is unnecessary for javascript resources как исправить
  • The steam anticheat servers are not responding unturned как исправить
  • The transport error code was 0x80040217
  • The server requested authentication method unknown to the client ошибка
  • The server encountered an internal unspecified error that prevented it from fulfilling the request