Ошибка cs0246 unity

1 vote and 12 comments so far on Reddit

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.

Egor12

0 / 0 / 0

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

Сообщений: 20

1

18.01.2021, 14:23. Показов 40499. Ответов 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



529 / 341 / 196

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

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

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



529 / 341 / 196

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

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

06.02.2022, 16:18

17

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



0



I have two scripts, one is located at:

Assets / Scriptable Objects / …

while the other one is located at:

Assets / Scripts / …

I have the first script encapsulated on a namespace.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using VoidlessNodes.LevelFlowNodes;

namespace VoidlessUtilities
{
[CreateAssetMenu]
public class LevelFlowData : BaseNodeEditorData<BaseLevelNode, LevelFlowEditorAttributes>
{
    private const string MENU_ITEM_PATH = "Create / ScriptableObjects / LevelFlowData";
    private const string NEW_ASSET_PATH = "ScriptableObjects / Level Flow Data";

    [SerializeField] private string _name;
    private RootLevelNode _root;

    /// <summary>Gets and Sets name property.</summary>
    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    /// <summary>Gets and Sets root property.</summary>
    public RootLevelNode root
    {
        get { return _root; }
        set { _root = value; }
    }

    [MenuItem(MENU_ITEM_PATH)]
    public static void CreateAsset()
    {
        LevelFlowData scriptableObject = ScriptableObject.CreateInstance<LevelFlowData>() as LevelFlowData;
        AssetDatabase.CreateAsset(scriptableObject, AssetDatabase.GenerateUniqueAssetPath(NEW_ASSET_PATH));
    }

    public BaseLevelFlowNode GetLevelFlow()
    {
        BaseLevelFlowNode rootLevelFlow = null;

        if(root != null)
        {
            rootLevelFlow = root.GetNode();
        }
        else
        {
            Debug.LogError("[LevelFlowData] Data has no RootLevelFlowNode saved");
        }

        return rootLevelFlow as RootLevelFlowNode;
    }
}
}

And the other one is using the same namespace, which is a namespace I use for my custom scripts, but the only difference is that LevelFlowData’s location is not under Scripts.

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

public class TestLevelController : Singleton<TestLevelController>
{
    [SerializeField] private LevelFlowData _levelFlowData;
    [SerializeField] private List<GameObject> _testViews;

    /// <summary>Gets and Sets levelFlowData property.</summary>
    public LevelFlowData levelFlowData
    {
        get { return _levelFlowData; }
        protected set { _levelFlowData = value; }
    }

    /// <summary>Gets and Sets testViews property.</summary>
    public List<GameObject> testViews
    {
        get { return _testViews; }
        set { _testViews = value; }
    }

#region UnityMethods:
    void OnEnable()
    {
        BaseInteractable.onTriggeredEvent += (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    void OnDisable()
    {
        BaseInteractable.onTriggeredEvent -= (int _eventID, bool _triggered)=> { Debug.Log("[TestLevelController] Event Triggered: " + _eventID); };
    }

    /// <summary>TestLevelController's' instance initialization.</summary>
    void Awake()
    {

    }

    /// <summary>TestLevelController's starting actions before 1st Update frame.</summary>
    void Start ()
    {

    }

    /// <summary>TestLevelController's tick at each frame.</summary>
    void Update ()
    {

    }
#endregion

#region PublicMethods:
    public void EnableView(int _index)
    {
        testViews.SetAllActive(false);
        testViews[_index].SetActive(true);
    }
#endregion

#region PrivateMethods:

#endregion
}

Do I need to move LevelFlowData to Scripts, and make platform independet compilation (e.g., #if UNITY_EDITOR) encapsulation for UnityEditor namespace usage? Or is there another point I am missing?

This is the specific error log:

Assets/Scripts/Scene Controllers/TestLevelController.cs(10,27): error CS0246: The type or namespace name `LevelFlowData’ could not be found. Are you missing an assembly reference?

Thanks in advance.

error CS0246 [РЕШЕНО]

The type or namespace name `SmoothFollow’ could not be found.

  1. public class Player : MonoBehaviour { 
  2. GameObject player; 
  3. void Start () { 
  4. player = GameObject.Find(«PlayerCam»); 
  5. player.GetComponent<SmoothFollow>().target = … 
  6.  
  7.  

ругается что у GameObject нет <SmoothFollow>. и если руками набрать player.GetComponent< то в списке «подсказок» нет этого скрипта.
на скришоте видно,что оба скрипта (и тот что выше, и SmoothFollow) есть у этого объекта

У вас нет доступа для просмотра вложений в этом сообщении.

Последний раз редактировалось Drui7 27 дек 2012, 10:42, всего редактировалось 2 раз(а).

я водитель НЛО (=

Drui7
UNец
 
Сообщения: 27
Зарегистрирован: 11 июн 2012, 18:12

Re: error CS0246

Сообщение BornFoRdeatH 27 дек 2012, 10:18

Дайте полный листинг кода

Не бойся, если ты один, бойся, если ты ноль.

BornFoRdeatH
Адепт
 
Сообщения: 2377
Зарегистрирован: 22 окт 2011, 23:41
Откуда: Украина
Skype: bornfordeath

Re: error CS0246

Сообщение Drui7 27 дек 2012, 10:22

BornFoRdeatH писал(а):Дайте полный листинг кода

  1. public GameObject player,hero; 
  2.  
  3. …. 
  4.  
  5. player = GameObject.Find(«PlayerCam»); 
  6. hero= Instantiate(GameObject.Find («Hero»+Hero)) as GameObject; 
  7. player.GetComponent<SmoothFollow>().target = hero.transform; 
  8.  
  9.  

кода много, остальное не касается проблемы. ругается конкретно на GetComponent<SmoothFollow>()

при создании проекта я почти ничего не брал из стандартных скриптов. SmoothFollow.js просто копировал с другого проекта в папку с этим проектом,затем Drag-and-drop

я водитель НЛО (=

Drui7
UNец
 
Сообщения: 27
Зарегистрирован: 11 июн 2012, 18:12

Re: error CS0246

Сообщение Drui7 27 дек 2012, 10:42

решено, копировал еще 2 скрипта для камеры в этот проект и всё ок стало

я водитель НЛО (=

Drui7
UNец
 
Сообщения: 27
Зарегистрирован: 11 июн 2012, 18:12


Вернуться в Почемучка

Кто сейчас на конференции

Сейчас этот форум просматривают: GoGo.Ru [Bot] и гости: 27



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка cs0234 unity
  • Ошибка cs0103 unity
  • Ошибка cs0029 юнити
  • Ошибка cs0004 pubg на ps5
  • Ошибка crystal process died

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии