Ошибка cs1001 требуется идентификатор

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
70
71
72
73
74
75
76
77
78
79
80
public void RadarOnGUI()
        {
            Visuals.RadarList.Clear();
            Rect radarRect = MenuHandler.RadarRect;
            Vector2 vector;
            vector..ctor(radarRect.center.x, radarRect.center.y + radarRect.height / 2f - 10f);
            Vector2 vector2;
            vector2..ctor(radarRect.center.x + radarRect.width / 2f - 10f, radarRect.center.y);
            Vector2 vector3;
            vector3..ctor(vector.x, vector2.y);
            int num = 20;
            float num2 = Math.Abs(radarRect.center.x - vector2.x);
            float num3 = num2 / (float)num;
            Vector3 position = Camera.main.transform.position;
            List<Zombie> list = new List<Zombie>();
            foreach (ZombieRegion zombieRegion in ZombieManager.regions)
            {
                foreach (Zombie item in zombieRegion.zombies)
                {
                    list.Add(item);
                }
            }
            foreach (Zombie zombie in list)
            {
                Vector2 vector4;
                vector4..ctor(zombie.transform.position.x - position.x, zombie.transform.position.z - position.z);
                float num4 = (float)Math.Round((double)(vector4.x * num3), 0);
                float num5 = (float)Math.Round((double)(vector4.y * num3), 0);
                num4 = -num4;
                Vector2 item2;
                item2..ctor(vector3.x + num4, vector3.y + num5);
                Log.l(vector3.ToString());
                Log.l(item2.ToString());
                Visuals.RadarList.Add(item2);
            }
            GUI.skin = HackDirector.sSkin;
            GUI.depth = 999;
            radarRect = MenuHandler.RadarRect;
            Vector2 vector5;
            vector5..ctor(radarRect.center.x, radarRect.center.y - radarRect.height / 2f + 20f);
            Vector2 vector6;
            vector6..ctor(radarRect.center.x - radarRect.width / 2f + 10f, radarRect.center.y);
            Vector2 vector7;
            vector7..ctor(vector6.x, vector.y);
            Vector2 vector8;
            vector8..ctor(vector2.x, vector.y);
            Vector2 vector9;
            vector9..ctor(vector6.x, vector5.y);
            Vector2 vector10;
            vector10..ctor(vector2.x, vector5.y);
            GL.PushMatrix();
            GL.Begin(1);
            this.DrawingMaterial.SetPass(0);
            GL.End();
            GL.PopMatrix();
            GL.PushMatrix();
            GL.Begin(1);
            this.DrawingMaterial.SetPass(0);
            GL.Color(Color.white);
            GL.Vertex3(vector.x, vector.y, 0f);
            GL.Vertex3(vector5.x, vector5.y, 0f);
            GL.Vertex3(vector6.x, vector6.y, 0f);
            GL.Vertex3(vector2.x, vector2.y, 0f);
            GL.Color(Color.black);
            GL.Vertex3(vector7.x, vector7.y, 0f);
            GL.Vertex3(vector8.x, vector8.y, 0f);
            GL.Vertex3(vector8.x, vector8.y, 0f);
            GL.Vertex3(vector10.x, vector10.y, 0f);
            GL.Vertex3(vector10.x, vector10.y, 0f);
            GL.Vertex3(vector9.x, vector9.y, 0f);
            GL.Vertex3(vector9.x, vector9.y, 0f);
            GL.Vertex3(vector7.x, vector7.y, 0f);
            GL.Color(Color.green);
            foreach (Vector2 input in Visuals.RadarList)
            {
                this.DrawSquare(input);
            }
            GL.End();
            GL.PopMatrix();
        }

I’m new to programming and am taking a C# class. I am getting compiler error CS1001 when I try to write this program.

I read the Compiler Error description (link below), but I’m really not getting it. What am I doing wrong?

http://msdn.microsoft.com/en-us/library/b839hwk4.aspx

Here is my source code:

using System;
public class InputMethodDemoTwo
{
   public static void Main()
   {
      int first, second;
      InputMethod(out first, out second); 
      Console.WriteLine("After InputMethod first is {0}", first);
      Console.WriteLine("and second is {0}", second);
   }
   public static void InputMethod(out first, out second) 
   // The error is citing the line above this note.
   {
      one = DataEntry("first"); 
      two = DataEntry("second");
   }
      public static void DataEntry(out int one, out int two)
      {
         string s1, s2;
         Console.Write("Enter first integer ");
         s1 = Console.ReadLine();
         Console.Write("Enter second integer ");
         s2 = Console.ReadLine();
         one = Convert.ToInt32(s1);
         two = Convert.ToInt32(s2);
      }
}

According to the instructions, I’m supposed to have a method b (InputData) which pulls statements from method c (DataEntry)… Here are the instructions:

The InputMethod()in the InputMethodDemo program in Figure 6-24 contains repetitive
code that prompts the user and retrieves integer values. Rewrite the program so the
InputMethod()calls another method to do the work. The rewritten InputMethod()
will need to contain only two statements:

one = DataEntry(«first»);

two = DataEntry(«second»);

Save the new program as InputMethodDemo2.cs.»

The InputMethodDemo they are referring to is the same program, except that it calls only one method (the InputMethod) instead of two.

The text I referred to above is «Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell»

Any advice/ help would be greatly appreciated.

here is my player attach code for moving platforms:

I’m getting an error CS1001: Identifier expected for some reason ant youtube is not helping me…

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

public class PlayerAttach : MonoBehaviour

{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        function OnTriggerEnter(other.Collider){

            if (other.gameObject.tag == "player")
            {
                transform.parent = other.transform;

            }
        }


        function OnTriggerExit(other.Collider){
            if (other.gameObject.tag == "player")
            {
                transform.parent = null;

            }
        }
    }
}

asked Jul 13, 2021 at 15:05

The_Game_Designer's user avatar

3

What you have is unityscript which is long deprecated and not compatible with c#!

And in general do not nest MonoBehaviour messages under Update! Otherwise the messaging system won’t find them and they are never called at all.

Your class should look like

public class PlayerAttach : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        // Rather use CompareTag instead of ==
        // the latter fails silently in case of s typo making your debugging live only harder
        if (!other.CompareTag("player")) return;
        
        transform.parent = other.transform;
    }

    private void OnTriggerExit(Collider other)
    {
        if (!other.CompareTag("player")) return;
        
        transform.parent = null;
    }
}

Further, a logical question: How exactly do you expect the player object leaving this collider if you make it a parent so whenever the player object moves this object moves along with it?

answered Jul 13, 2021 at 15:27

derHugo's user avatar

derHugoderHugo

76.9k9 gold badges67 silver badges105 bronze badges

here is my player attach code for moving platforms:

I’m getting an error CS1001: Identifier expected for some reason ant youtube is not helping me…

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

public class PlayerAttach : MonoBehaviour

{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        function OnTriggerEnter(other.Collider){

            if (other.gameObject.tag == "player")
            {
                transform.parent = other.transform;

            }
        }


        function OnTriggerExit(other.Collider){
            if (other.gameObject.tag == "player")
            {
                transform.parent = null;

            }
        }
    }
}

asked Jul 13, 2021 at 15:05

The_Game_Designer's user avatar

3

What you have is unityscript which is long deprecated and not compatible with c#!

And in general do not nest MonoBehaviour messages under Update! Otherwise the messaging system won’t find them and they are never called at all.

Your class should look like

public class PlayerAttach : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        // Rather use CompareTag instead of ==
        // the latter fails silently in case of s typo making your debugging live only harder
        if (!other.CompareTag("player")) return;
        
        transform.parent = other.transform;
    }

    private void OnTriggerExit(Collider other)
    {
        if (!other.CompareTag("player")) return;
        
        transform.parent = null;
    }
}

Further, a logical question: How exactly do you expect the player object leaving this collider if you make it a parent so whenever the player object moves this object moves along with it?

answered Jul 13, 2021 at 15:27

derHugo's user avatar

derHugoderHugo

76.9k9 gold badges67 silver badges105 bronze badges

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS1001

Compiler Error CS1001

07/20/2015

CS1001

CS1001

327ad669-9c20-4fe8-a771-234878dbb90e

Compiler Error CS1001

Identifier expected

You did not supply an identifier. An identifier is the name of a class, struct, namespace, method, variable, and so on, that you provide.

The following example declares a simple class but does not give the class a name:

public class //CS1001
{
    public int Num { get; set; }
    void MethodA() {}
}

The following sample generates CS1001 because, when declaring an enum, you must specify members:

public class Program
{
    enum Colors
    {
        'a', 'b' // CS1001, 'a' is not a valid int identifier
        // The following line shows examples of valid identifiers:
        // Blue, Red, Orange
    };

    public static void Main()
    {
    }
}

Parameter names are required even if the compiler doesn’t use them, for example, in an interface definition. These parameters are required so that programmers who are consuming the interface know something about what the parameters mean.

interface IMyTest
{
    void TestFunc1(int, int);  // CS1001
    // Use the following line instead:
    // void TestFunc1(int a, int b);
}

class CMyTest : IMyTest
{
    void IMyTest.TestFunc1(int a, int b)
    {
    }
}

See also

  • Operators and expressions
  • Types

I’m new to programming and am taking a C# class. I am getting compiler error CS1001 when I try to write this program.

I read the Compiler Error description (link below), but I’m really not getting it. What am I doing wrong?

http://msdn.microsoft.com/en-us/library/b839hwk4.aspx

Here is my source code:

using System;
public class InputMethodDemoTwo
{
   public static void Main()
   {
      int first, second;
      InputMethod(out first, out second); 
      Console.WriteLine("After InputMethod first is {0}", first);
      Console.WriteLine("and second is {0}", second);
   }
   public static void InputMethod(out first, out second) 
   // The error is citing the line above this note.
   {
      one = DataEntry("first"); 
      two = DataEntry("second");
   }
      public static void DataEntry(out int one, out int two)
      {
         string s1, s2;
         Console.Write("Enter first integer ");
         s1 = Console.ReadLine();
         Console.Write("Enter second integer ");
         s2 = Console.ReadLine();
         one = Convert.ToInt32(s1);
         two = Convert.ToInt32(s2);
      }
}

According to the instructions, I’m supposed to have a method b (InputData) which pulls statements from method c (DataEntry)… Here are the instructions:

The InputMethod()in the InputMethodDemo program in Figure 6-24 contains repetitive
code that prompts the user and retrieves integer values. Rewrite the program so the
InputMethod()calls another method to do the work. The rewritten InputMethod()
will need to contain only two statements:

one = DataEntry(«first»);

two = DataEntry(«second»);

Save the new program as InputMethodDemo2.cs.»

The InputMethodDemo they are referring to is the same program, except that it calls only one method (the InputMethod) instead of two.

The text I referred to above is «Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell»

Any advice/ help would be greatly appreciated.

Я полный новичок, пытающийся изучить C#, создавая моды для игры под названием RimWorld. Я получил исходный код мода, который делает что-то похожее на то, что я пытаюсь сделать, и настраивал его, чтобы увидеть, что я могу заставить работать. Следующая ошибка поставила меня в тупик, так как рассматриваемый фрагмент кода не изменен из исходного кода, который я получил из работающего мода. Я также недостаточно хорошо знаю C#, чтобы знать, что конкретно ищет Visual Studio, а копирование решений из похожих вопросов не дало никаких результатов.

Ошибка: CS1001 — Ожидается идентификатор — Файл: GetPawnThing.cs — Строка 20

using System;
using RimWorld;
using Verse;

namespace VehicleSpawnerName
{
    // Token: 0x02000002 RID: 2
    public class GetPawnThing : MoteThrown
    {
        // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
        public override void Tick()
        {
            bool flag = base.Map == null;
            if (flag)
            {
                this.Destroy(0);
            }
            PawnKindDef Vehicle_Name = PawnKindDefOf.Vehicle_Name;
            PawnGenerationRequest pawnGenerationRequest;
            pawnGenerationRequest..ctor(Vehicle_Name, null, 2, -1, true, false, false, false, true, false, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);
            Pawn pawn = PawnGenerator.GeneratePawn(pawnGenerationRequest);
            pawn.ageTracker.AgeBiologicalTicks = 70000000L;
            GenSpawn.Spawn(pawn, base.Position, base.Map, 0);
            this.Destroy(0);
        }
    }
}

Рассматриваемая строка (согласно отчету об ошибке):

pawnGenerationRequest..ctor(Vehicle_Name, null, 2, -1, true, false, false, false, true, false, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);

Любая помощь приветствуется!

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

public class PlaerMufment : MonoBehaviour {

    CharacterController cc;
    Vector3 moveVec;

    float speed = 5;

    int laneNamber = 1,
        lanesCount = 2;

    public float FirstlanePos,
                 LaneDistance,
                 SideSpeed;


    void Start()
    {
        cc = GetComponent<CharacterController>();
        moveVec = new Vector3(1, 0, 0);
    }

    


    void Update()
    {
        moveVec.x *= speed;
        moveVec *= Time.deltaTime;

        float imput = Input.GetAxis("Horizontal");

        if (Mathf.Abs(input) >.if);
        {
            laneNamber += (int)Matht.Sign(input);
            laneNamber = Mathf.Clamp(laneNamber, 0, lanesCount);
        }

        Vectore3 newPos = transfore.position;
        newPos.z = Mathf.Lerp(newPos.z, FirstLanePos + (laneNamber * LaneDistance), Time.deltaTime * SideSpeed);
        transform.position = newPos;

        cc.Move(moveVec);
    }
}

AssetsSkriptPlaerMufment.cs(36,31): error CS1525: Invalid expression term ‘.’
AssetsSkriptPlaerMufment.cs(36,32): error CS1001: Identifier expected
AssetsSkriptPlaerMufment.cs(36,32): error CS1026: ) expected
AssetsSkriptPlaerMufment.cs(36,34): error CS1003: Syntax error, ‘(‘ expected
AssetsSkriptPlaerMufment.cs(36,34): error CS1525: Invalid expression term ‘)’

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS1001

Compiler Error CS1001

07/20/2015

CS1001

CS1001

327ad669-9c20-4fe8-a771-234878dbb90e

Compiler Error CS1001

Identifier expected

You did not supply an identifier. An identifier is the name of a class, struct, namespace, method, variable, and so on, that you provide.

The following example declares a simple class but does not give the class a name:

public class //CS1001
{
    public int Num { get; set; }
    void MethodA() {}
}

The following sample generates CS1001 because, when declaring an enum, you must specify members:

public class Program
{
    enum Colors
    {
        'a', 'b' // CS1001, 'a' is not a valid int identifier
        // The following line shows examples of valid identifiers:
        // Blue, Red, Orange
    };

    public static void Main()
    {
    }
}

Parameter names are required even if the compiler doesn’t use them, for example, in an interface definition. These parameters are required so that programmers who are consuming the interface know something about what the parameters mean.

interface IMyTest
{
    void TestFunc1(int, int);  // CS1001
    // Use the following line instead:
    // void TestFunc1(int a, int b);
}

class CMyTest : IMyTest
{
    void IMyTest.TestFunc1(int a, int b)
    {
    }
}

See also

  • Operators and expressions
  • Types

I’m new to programming and am taking a C# class. I am getting compiler error CS1001 when I try to write this program.

I read the Compiler Error description (link below), but I’m really not getting it. What am I doing wrong?

http://msdn.microsoft.com/en-us/library/b839hwk4.aspx

Here is my source code:

using System;
public class InputMethodDemoTwo
{
   public static void Main()
   {
      int first, second;
      InputMethod(out first, out second); 
      Console.WriteLine("After InputMethod first is {0}", first);
      Console.WriteLine("and second is {0}", second);
   }
   public static void InputMethod(out first, out second) 
   // The error is citing the line above this note.
   {
      one = DataEntry("first"); 
      two = DataEntry("second");
   }
      public static void DataEntry(out int one, out int two)
      {
         string s1, s2;
         Console.Write("Enter first integer ");
         s1 = Console.ReadLine();
         Console.Write("Enter second integer ");
         s2 = Console.ReadLine();
         one = Convert.ToInt32(s1);
         two = Convert.ToInt32(s2);
      }
}

According to the instructions, I’m supposed to have a method b (InputData) which pulls statements from method c (DataEntry)… Here are the instructions:

The InputMethod()in the InputMethodDemo program in Figure 6-24 contains repetitive
code that prompts the user and retrieves integer values. Rewrite the program so the
InputMethod()calls another method to do the work. The rewritten InputMethod()
will need to contain only two statements:

one = DataEntry(«first»);

two = DataEntry(«second»);

Save the new program as InputMethodDemo2.cs.»

The InputMethodDemo they are referring to is the same program, except that it calls only one method (the InputMethod) instead of two.

The text I referred to above is «Microsoft® Visual C#® 2008, An Introduction to Object-Oriented Programming, 3e, Joyce Farrell»

Any advice/ help would be greatly appreciated.

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
70
71
72
73
74
75
76
77
78
79
80
public void RadarOnGUI()
        {
            Visuals.RadarList.Clear();
            Rect radarRect = MenuHandler.RadarRect;
            Vector2 vector;
            vector..ctor(radarRect.center.x, radarRect.center.y + radarRect.height / 2f - 10f);
            Vector2 vector2;
            vector2..ctor(radarRect.center.x + radarRect.width / 2f - 10f, radarRect.center.y);
            Vector2 vector3;
            vector3..ctor(vector.x, vector2.y);
            int num = 20;
            float num2 = Math.Abs(radarRect.center.x - vector2.x);
            float num3 = num2 / (float)num;
            Vector3 position = Camera.main.transform.position;
            List<Zombie> list = new List<Zombie>();
            foreach (ZombieRegion zombieRegion in ZombieManager.regions)
            {
                foreach (Zombie item in zombieRegion.zombies)
                {
                    list.Add(item);
                }
            }
            foreach (Zombie zombie in list)
            {
                Vector2 vector4;
                vector4..ctor(zombie.transform.position.x - position.x, zombie.transform.position.z - position.z);
                float num4 = (float)Math.Round((double)(vector4.x * num3), 0);
                float num5 = (float)Math.Round((double)(vector4.y * num3), 0);
                num4 = -num4;
                Vector2 item2;
                item2..ctor(vector3.x + num4, vector3.y + num5);
                Log.l(vector3.ToString());
                Log.l(item2.ToString());
                Visuals.RadarList.Add(item2);
            }
            GUI.skin = HackDirector.sSkin;
            GUI.depth = 999;
            radarRect = MenuHandler.RadarRect;
            Vector2 vector5;
            vector5..ctor(radarRect.center.x, radarRect.center.y - radarRect.height / 2f + 20f);
            Vector2 vector6;
            vector6..ctor(radarRect.center.x - radarRect.width / 2f + 10f, radarRect.center.y);
            Vector2 vector7;
            vector7..ctor(vector6.x, vector.y);
            Vector2 vector8;
            vector8..ctor(vector2.x, vector.y);
            Vector2 vector9;
            vector9..ctor(vector6.x, vector5.y);
            Vector2 vector10;
            vector10..ctor(vector2.x, vector5.y);
            GL.PushMatrix();
            GL.Begin(1);
            this.DrawingMaterial.SetPass(0);
            GL.End();
            GL.PopMatrix();
            GL.PushMatrix();
            GL.Begin(1);
            this.DrawingMaterial.SetPass(0);
            GL.Color(Color.white);
            GL.Vertex3(vector.x, vector.y, 0f);
            GL.Vertex3(vector5.x, vector5.y, 0f);
            GL.Vertex3(vector6.x, vector6.y, 0f);
            GL.Vertex3(vector2.x, vector2.y, 0f);
            GL.Color(Color.black);
            GL.Vertex3(vector7.x, vector7.y, 0f);
            GL.Vertex3(vector8.x, vector8.y, 0f);
            GL.Vertex3(vector8.x, vector8.y, 0f);
            GL.Vertex3(vector10.x, vector10.y, 0f);
            GL.Vertex3(vector10.x, vector10.y, 0f);
            GL.Vertex3(vector9.x, vector9.y, 0f);
            GL.Vertex3(vector9.x, vector9.y, 0f);
            GL.Vertex3(vector7.x, vector7.y, 0f);
            GL.Color(Color.green);
            foreach (Vector2 input in Visuals.RadarList)
            {
                this.DrawSquare(input);
            }
            GL.End();
            GL.PopMatrix();
        }

Я полный новичок, пытающийся изучить C#, создавая моды для игры под названием RimWorld. Я получил исходный код мода, который делает что-то похожее на то, что я пытаюсь сделать, и настраивал его, чтобы увидеть, что я могу заставить работать. Следующая ошибка поставила меня в тупик, так как рассматриваемый фрагмент кода не изменен из исходного кода, который я получил из работающего мода. Я также недостаточно хорошо знаю C#, чтобы знать, что конкретно ищет Visual Studio, а копирование решений из похожих вопросов не дало никаких результатов.

Ошибка: CS1001 — Ожидается идентификатор — Файл: GetPawnThing.cs — Строка 20

Рассматриваемая строка (согласно отчету об ошибке):

Любая помощь приветствуется!

Декомпиляция двоичного файла не гарантирует получение корректного кода. Эта строка пытается вызвать конструктор.

Это хорошо знать, я бы не знал достаточно, чтобы сказать разницу. Означает ли это, что я не могу ожидать, что этот код вообще сработает?

Вам нужно интерпретировать то, что он пытается сделать, и переписать его в правильный код. Вы знаете, как вызвать конструктор объекта?

Нет, но я прочитаю несколько руководств о том, как это сделать. Спасибо, что указали мне правильное направление.

Я дам вам подсказку. pawnGenerationRequest..ctor(. ) — это декомпилятор, говорящий «вызвать конструктор PawnGenerationRequest с этими аргументами». Если вы не можете получить его, вернитесь, и мы можем помочь дальше. Это хорошее учебное упражнение.

Источник

Неустранимая ошибка C1001

ВНУТРЕННЯЯ ОШИБКА КОМПИЛЯТОРА ( файл компилятора, номер строки)

Компилятор не может создать правильный код для конструкции, часто из-за сочетания определенного выражения и параметра оптимизации или проблемы при анализе. Если указанный файл компилятора содержит сегмент пути в формате UTC или C2, вероятно, это ошибка оптимизации. Если файл содержит сегмент пути cxxfe или c1xx или msc1.cpp, вероятно, это ошибка средства синтаксического анализа. Если файл с именем cl.exe, другие сведения отсутствуют.

Часто можно устранить проблему оптимизации, удалив один или несколько вариантов оптимизации. Чтобы определить, какой вариант неисправен, удаляйте параметры по одному и перекомпилируйте, пока сообщение об ошибке не исчезнет. Чаще всего отвечают параметры /Og (глобальная оптимизация) и /Oi (создание встроенных функций). Определив, какой вариант оптимизации отвечает, вы можете отключить его вокруг функции, в которой возникает ошибка, с помощью директивы optimize pragma и продолжить использовать параметр для остальной части модуля. Дополнительные сведения о параметрах оптимизации см. в разделе Рекомендации по оптимизации.

Если оптимизация не несет ответственности за ошибку, попробуйте переписать строку, в которой сообщается ошибка, или несколько строк кода, окружающих ее. Чтобы просмотреть код так, как компилятор видит его после предварительной обработки, можно использовать параметр /P (Предварительная обработка к файлу).

Дополнительные сведения о том, как изолировать источник ошибки и как сообщить о внутренней ошибке компилятора в корпорацию Майкрософт, см. в статье Как сообщить о проблеме с набором инструментов Visual C++.

Источник

here is my player attach code for moving platforms:

I’m getting an error CS1001: Identifier expected for some reason ant youtube is not helping me…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttach : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
function OnTriggerEnter(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = other.transform;
}
}
function OnTriggerExit(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = null;
}
}
}
}

asked Jul 13, 2021 at 15:05

The_Game_Designer's user avatar

3

What you have is unityscript which is long deprecated and not compatible with c#!

And in general do not nest MonoBehaviour messages under Update! Otherwise the messaging system won’t find them and they are never called at all.

Your class should look like

public class PlayerAttach : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
// Rather use CompareTag instead of ==
// the latter fails silently in case of s typo making your debugging live only harder
if (!other.CompareTag("player")) return;
transform.parent = other.transform;
}
private void OnTriggerExit(Collider other)
{
if (!other.CompareTag("player")) return;
transform.parent = null;
}
}

Further, a logical question: How exactly do you expect the player object leaving this collider if you make it a parent so whenever the player object moves this object moves along with it?

answered Jul 13, 2021 at 15:27

derHugo's user avatar

derHugoderHugo

77.4k9 gold badges67 silver badges105 bronze badges

here is my player attach code for moving platforms:

I’m getting an error CS1001: Identifier expected for some reason ant youtube is not helping me…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttach : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
function OnTriggerEnter(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = other.transform;
}
}
function OnTriggerExit(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = null;
}
}
}
}

asked Jul 13, 2021 at 15:05

The_Game_Designer's user avatar

3

What you have is unityscript which is long deprecated and not compatible with c#!

And in general do not nest MonoBehaviour messages under Update! Otherwise the messaging system won’t find them and they are never called at all.

Your class should look like

public class PlayerAttach : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
// Rather use CompareTag instead of ==
// the latter fails silently in case of s typo making your debugging live only harder
if (!other.CompareTag("player")) return;
transform.parent = other.transform;
}
private void OnTriggerExit(Collider other)
{
if (!other.CompareTag("player")) return;
transform.parent = null;
}
}

Further, a logical question: How exactly do you expect the player object leaving this collider if you make it a parent so whenever the player object moves this object moves along with it?

answered Jul 13, 2021 at 15:27

derHugo's user avatar

derHugoderHugo

77.4k9 gold badges67 silver badges105 bronze badges

  • Remove From My Forums
  • Question

  • User225301687 posted

    hi guys…i got this error:

    Compiler Error Message: CS1001: Identifier expected
    

    from this set of code:

    var reqcategory=""; 
    foreach(Request["category"] as reqcategory)
    {
    var sql5 = "SELECT Type.PreReq1, Type.PreReq2, (CASE WHEN (Type.PreReq1 IS NOT NULL) AND (PermitApp1.RPClass IS NULL) AND (PermitApp1.RPCategory IS NULL) THEN 1 ELSE 0 END) AS missing1, (CASE WHEN (Type.PreReq2 IS NOT NULL) AND (PermitApp2.RPClass IS NULL) AND (PermitApp2.RPCategory IS NULL) THEN 1 ELSE 0 END) AS missing2 FROM Type LEFT JOIN PermitApp AS PermitApp1 ON (Type.PreReq1=PermitApp1.RPClass) OR (Type.PreReq1=PermitApp1.RPCategory) AND ( PermitApp1.CDSID = @0 ) AND (PermitApp1.MDecision='1') LEFT JOIN PermitApp AS PermitApp2 ON (Type.PreReq2=PermitApp2.RPClass) OR (Type.PreReq2=PermitApp2.RPCategory) AND ( PermitApp2.CDSID = @1 ) AND (PermitApp2.MDecision='1') WHERE Type.PType = @2";
    var result = db.QuerySingle(sql5, myCDSID, myCDSID, reqcategory);
    var miss1 = result.missing1;
    var miss2 = result.missing2;
    }

    The error happens to fall on this line: 

    foreach(Request["category"] as reqcategory)

    as highlighted by the compiler.

    How should i declare a identifier?? anyway it is a string i think in the database it is nvarchar.

Answers

  • User44080657 posted

    Yea i dont think that is going to work that way. Try this. For each is mean to loop through a collection, meaning you need to get the collection first then loop through it

    var reqcategory=Request["category"];
    foreach (var cat in reqctegory)
    {
    //the rest of your code here...
    }
    
    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1853794821 posted

    «or» is not a valid operator in C#

    use «!!»

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

I am trying to create a program to copy all the files from one directory to another. But I am running in a basic issue. It says indentifier expected when I try to compile on line 52.

public bool RecursiveCopy()
{
    string origDir = @"D:Documents and SettingsDubMy DocumentsHoN Updatestest";
    string destDir = @"C:GamesHoN";
    bool status = false;

    //get all the info about the original directory
    var dirInfo = new DirectoryInfo(origDir);

    //retrieve all the _fileNames in the original directory
    var files = dirInfo.GetFiles(origDir);

    //always use a try...catch to deal 
    //with any exceptions that may occur
    try
    {
        //loop through all the file names and copy them
        foreach (string file in Directory.GetFiles(origDir))
        {
            var origFile = new FileInfo(file);
            var destFile = new FileInfo(file.Replace(origDir, destDir));

            //copy the file, use the OverWrite overload to overwrite
            //destination file if it exists

            System.IO.File.Copy(origFile.FullName, destFile.FullName, true);

            //TODO: If you dont want to remove the original
            //_fileNames comment this line out
            File.Delete(origFile.FullName);
            status = true;
        }
        Console.WriteLine("All files in " + origDir + " copied successfully!");
    }
    catch (Exception ex)
    {
        status = false;

        //handle any errors that may have occurred
        Console.WriteLine(ex.Message);
    }
    return status;
}

public string origDir = @"D:Documents and SettingsDubMy DocumentsHoN Updatestest"; // ERROR HERE
public string destDir = @"C:GamesHoN"; // ERROR HERE

private static void RecursiveCopy(origDir, destDir)
{
    Console.WriteLine("done");
    Console.ReadLine();
}

AustinWBryan's user avatar

AustinWBryan

3,2493 gold badges23 silver badges42 bronze badges

asked Aug 4, 2009 at 0:07

Steven's user avatar

0

You did not give type identifiers to your argument list here

static void RecursiveCopy(origDir, destDir)

should be

static void RecursiveCopy(string origDir, string destDir)

answered Aug 4, 2009 at 0:10

Ed S.'s user avatar

Ed S.Ed S.

122k22 gold badges182 silver badges263 bronze badges

0

Your method RecursiveCopy has two parameters listed without their types. It should be this:

static void RecursiveCopy(string origDir, string destDir)

answered Aug 4, 2009 at 0:11

Sam Harwell's user avatar

Sam HarwellSam Harwell

97.4k20 gold badges208 silver badges279 bronze badges

0

Here is your problem:

static void RecursiveCopy(origDir, destDir)

You don’t specify the types for the parameters, perhaps you intended the following:

static void RecursiveCopy(string origDir, string destDir)

There are more issues however that I’ve noticed. It’s possible you’re still working on these, but from what you’ve posted:

  • You never call your RecursiveCopy method. Perhaps you meant to call it from Main() instead of declaring an overload with two parameters?

  • You declare two public fields origDir and destDir but then never use them. Instead you create two local variables in RecursiveCopy() and use these instead. Did you intend to create parameters or use the public fields instead?

  • Your copy is not actually true to its name of «recursive».

answered Aug 4, 2009 at 0:18

lc.'s user avatar

lc.lc.

113k20 gold badges158 silver badges186 bronze badges

1

cYou are missing the parameter types in the RecursiveCopy method declaration. Just Change

static void RecursiveCopy(origDir, destDir)

to

static void RecursiveCopy(String origDir, String destDir)

and all is fine.

answered Aug 4, 2009 at 0:17

Daniel Brückner's user avatar

Daniel BrücknerDaniel Brückner

58.9k16 gold badges98 silver badges143 bronze badges

Возможно, вам также будет интересно:

  • Ошибка cs0263 разделяемые объявления не должны указывать различные базовые классы
  • Ошибка cs0246 не удалось найти тип или имя пространства имен
  • Ошибка cs0161 не все пути к коду возвращают значение
  • Ошибка cs0121 неоднозначный вызов следующих методов или свойств
  • Ошибка cs0120 для нестатического поля метода или свойства требуется ссылка на объект

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

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