I’m having some trouble fixing this error. I’ve had it work before but as soon as I added a second GetKeyDown it stopped working. Sorry if I look stupid, I’m an extreme beginner.
using UnityEngine;
using System.Collections;
// Use this for initialization
void Start ()
{
public int moveSpeed = 5;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.D))
{
transform.Translate (Vector3.right * moveSpeed);
};
if (Input.GetKeyDown (KeyCode.A))
{
transform.Translate (Vector3.left * moveSpeed);
};
}
};
asked Jul 29, 2015 at 1:13
1
A) You are missing class declaration line (you still have closing bracket for it)
using UnityEngine;
using System.Collections;
public class Stuff : MonoBehaviour { // <-- you need class declaration (it must be the same name as file "Stuff.cs"
public int moveSpeed = 5; // <-- B) you need to declare this variable at this scope or else Update method won't be able to see it
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.D))
{
transform.Translate (Vector3.right * moveSpeed);
}
if (Input.GetKeyDown (KeyCode.A))
{
transform.Translate (Vector3.left * moveSpeed);
}
}
} //<-- also - no semicolons after the closing brackets
answered Jul 29, 2015 at 6:53
izeedizeed
1,7212 gold badges16 silver badges15 bronze badges
Why do you have semicolons everywhere? Anyway, thats not the problem.
// Use this for initialization
void Start ()
{
int moveSpeed = 5; // remove public
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.D))
{
transform.Translate (Vector3.right * moveSpeed);
}
if (Input.GetKeyDown (KeyCode.A))
{
transform.Translate (Vector3.left * moveSpeed);
}
}
Tell me if this works.
answered Jul 29, 2015 at 1:31
Souradeep NandaSouradeep Nanda
3,0262 gold badges34 silver badges43 bronze badges
1
Try changing it to:
public int moveSpeed;
void Start ()
{
moveSpeed = 5;
}
What I would really recommend is not to set the moveSpeed to 5 in the script but rather in the editor. Once you change the code to what I showed you then moveSpeed will show up in the editor inspector. Set it to whatever you want there. That way you can use the same script for objects with different speeds.
answered Jul 29, 2015 at 5:39
ReasurriaReasurria
1,69814 silver badges14 bronze badges
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Compiler Error CS1525 |
Compiler Error CS1525 |
07/20/2015 |
CS1525 |
CS1525 |
7913f589-2f2e-40bc-a27e-0b6930336484 |
Compiler Error CS1525
Invalid expression term ‘character’
The compiler detected an invalid character in an expression.
The following sample generates CS1525:
// CS1525.cs class x { public static void Main() { int i = 0; i = i + // OK - identifier 'c' + // OK - character (5) + // OK - parenthesis [ + // CS1525, operator not a valid expression element throw + // CS1525, keyword not allowed in expression void; // CS1525, void not allowed in expression } }
An empty label can also generate CS1525, as in the following sample:
// CS1525b.cs using System; public class MyClass { public static void Main() { goto FoundIt; FoundIt: // CS1525 // Uncomment the following line to resolve: // System.Console.Write("Hello"); } }
Проблема с скриптом! |
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
|
|
Antoffa 0 / 0 / 0 Регистрация: 31.03.2016 Сообщений: 37 |
||||
1 |
||||
10.09.2021, 16:45. Показов 4214. Ответов 14 Метки с# (Все метки)
Ошибка на main.cs(25,5): error CS1525: Unexpected symbol `<‘
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
10.09.2021, 16:45 |
Ответы с готовыми решениями:
Opencv error :-1: ошибка: main.o: undefined reference to symbol ‘_ZN2cv6String10deallocateEv’ error C2601: ‘main’ : local function definitions are illegal fatal error C1004: unexpected end of file found error C2601: ‘main’ :… 14 |
Модератор 13302 / 9586 / 2574 Регистрация: 21.04.2018 Сообщений: 28,283 Записей в блоге: 2 |
|
10.09.2021, 17:05 |
2 |
error CS1525: Unexpected symbol `<‘
0 |
zhunshun 603 / 445 / 196 Регистрация: 05.04.2015 Сообщений: 1,773 |
||||
10.09.2021, 17:13 |
3 |
|||
Antoffa,
0 |
Antoffa 0 / 0 / 0 Регистрация: 31.03.2016 Сообщений: 37 |
||||
10.09.2021, 17:18 [ТС] |
4 |
|||
Через if else правильно работает, необходимо преобразовать в switch, такая задача стояла
Добавлено через 4 минуты
0 |
1346 / 835 / 419 Регистрация: 06.02.2012 Сообщений: 2,603 |
|
10.09.2021, 17:26 |
5 |
Antoffa, Вам же выше написали, что swith не работает с операторами. Может вы не так поняли свою задачу?
0 |
0 / 0 / 0 Регистрация: 31.03.2016 Сообщений: 37 |
|
10.09.2021, 17:34 [ТС] |
6 |
Первоначально было через if else, но надо было изменить решение этой задачи, и поэтому подумал делать через switch. Как можно еще изменить данное решение ????
0 |
603 / 445 / 196 Регистрация: 05.04.2015 Сообщений: 1,773 |
|
10.09.2021, 17:38 |
7 |
Как можно еще изменить данное решение ???? А что мои вариант не подходит??
0 |
1465 / 1006 / 456 Регистрация: 30.10.2017 Сообщений: 2,793 |
|
10.09.2021, 17:46 |
8 |
case может только сравнить со значением или шаблоном. В C#9 этот код скомпилируется. Antoffa, если хотите, чтобы case работал способом, указанным вами, создайте консольное приложение с поддержкой .NET Core и в свойствах проекта укажите целевую рабочую среду .NET 5.0. Или используйте вместо
0 |
Элд Хасп Модератор 13302 / 9586 / 2574 Регистрация: 21.04.2018 Сообщений: 28,283 Записей в блоге: 2 |
||||
10.09.2021, 18:32 |
9 |
|||
В C#9 этот код скомпилируется. Ну, очевидно же, что TC не использует эту версию. Добавлено через 3 минуты
Как можно еще изменить данное решение ???? Примените условный оператор:
0 |
1465 / 1006 / 456 Регистрация: 30.10.2017 Сообщений: 2,793 |
|
10.09.2021, 18:33 |
10 |
Ну, очевидно же, что TC не использует эту версию. Однако код написал правильно. Это легко сделать, загуглив описание использования switch в справке Microsoft, к примеру. А вот то, что надо и соответствующую версию языка использовать при этом, уже не так очевидно.
Через if else правильно работает, необходимо преобразовать в switch, такая задача стояла Элд Хасп, к тому же в задании четко сказано, что нужно использовать для этого switch, а, значит, лекции могли проводиться по этой версии языка. Конечно, возможно все это мои догадки.
0 |
Модератор 13302 / 9586 / 2574 Регистрация: 21.04.2018 Сообщений: 28,283 Записей в блоге: 2 |
|
10.09.2021, 18:38 |
11 |
Antoffa, но уточните у преподавателя на каком платформе и версии Шарпа допустимо выполнять задание. Добавлено через 2 минуты
к тому же в задании четко сказано, что нужно использовать для этого switch Когда я отвечал, этого не было сказано.
1 |
1465 / 1006 / 456 Регистрация: 30.10.2017 Сообщений: 2,793 |
|
10.09.2021, 18:44 |
12 |
Кроме того, постом позже TC поправляется, в задании нужно сделать «по другому». Тогда может быть все банальнее, например, преподавателю не понравилось, что расчет формулы не вынесен в отдельный метод. Добавлено через 4 минуты
1 |
Antoffa 0 / 0 / 0 Регистрация: 31.03.2016 Сообщений: 37 |
||||
10.09.2021, 19:31 [ТС] |
13 |
|||
Вот так ???
0 |
Модератор 13302 / 9586 / 2574 Регистрация: 21.04.2018 Сообщений: 28,283 Записей в блоге: 2 |
|||||
10.09.2021, 19:33 |
14 |
||||
Вот так ??? Да. Добавлено через 21 секунду
Добавлено через 35 секунд
0 |
Antoffa 0 / 0 / 0 Регистрация: 31.03.2016 Сообщений: 37 |
||||
10.09.2021, 19:48 [ТС] |
15 |
|||
А можно данный вариант решить еще через цикл??
Добавлено через 1 минуту
А можно данный вариант решить еще через цикл??
0 |
Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
I am sure that every «{» has its equally paired «}» in my code, but the compiler keep telling me that Program.cs(20,40): error CS1525: Unexpected symbol `}’.
I wonder where my mistake is, and how can I fix it?
Program.cs
using System; namespace Treehouse.CodeChallenges { class Program { static void Main() { while(true) //loop started { Console.Write("Enter the number of times to print "Yay!": "); string entry = Console.ReadLine(); if(entry.ToLower()=="quit") { break; } else { int time = int.Parse(entry); //turn "string" into "int" int k; for(k = 0; k < time) //make the loop run k times { Console.Write("Yay!"); k = k + 1; continue; } } break; //leave the "while loop" since "for" is not satisfied } } } }
2 Answers
Your program «works», but deviates from the instructions.
This is a great example of how something that works (will compile an run) might not be what was asked for (satisfies the requirements). This has been a topic of many previous questions, but I’ll repost the info here:
People often over-think this one and get too creative, and their answer is rejected for a variety of reasons (some which don’t seem to make any sense).
Here are the secret «rules» you must follow for success on this one:
- Your program must ask for and accept input ONE TIME ONLY
- If the input validates, your program will perform exactly as in Task 1
- If the input does not validate, it will print the error message and exit
- Validation must be done by exception catching. There are other perfectly good methods that can be used for validation, but they will not pass this challenge
It looks like you have an extra loop that is violating the first and third «rule».
using System; namespace Treehouse.CodeChallenges { class Program { static void Main() { Console.Write("Enter the number of times to print "Yay!": "); int entry = int.Parse(Console.ReadLine()); for(int i=0;i<entry;i++) { Console.WriteLine("Yay!"); } } } }
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 ‘)’