Asked
3 years, 4 months ago
Viewed
14k times
I am creating a 2d platform game in the Unity Engine Version Num — 2018.4.9f1 with c# compiled with Visual Studio Version Num — 1.38.1.
The console in Unity Engine is showing two errors listed below with the code I have in the Visual Studio.
error CS1003: Syntax error, ‘(‘ expected
error CS1031: Type expected
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof)(Text))]
public class CountdownText : MonoBehaviour {
public delegate void CountdownFinished();
public static event CountdownFinished OnCountdownFinished;
Text countdown;
void OnEnable() {
countdown = GetComponent<Text>();
countdown.text = "3";
StartCoroutine("Countdown");
}
IEnumerator Countdown() {
int count = 3;
for (int i = 0; i < count; i++) {
countdown.text = (count - i).ToString();
yield return new WaitForSeconds(1);
}
OnCountdownFinished();
}
}
marc_s
722k173 gold badges1320 silver badges1443 bronze badges
asked Sep 24, 2019 at 3:49
2
RequireComponent(typeof)(Text))
is wrong. It should be RequireComponent(typeof(Text))
The typeof operator obtains the System.Type instance for a type.
answered Sep 24, 2019 at 3:55
Richard BarkerRichard Barker
1,1512 gold badges12 silver badges30 bronze badges
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public string firstName;
public string lastName;
public int birthYear;
// Start is called before the first frame update
void Start()
{
print("Your first name is : " + firstName + "and your last name is " + lastName);
print("Your initials are: " firstName[0] + lastName[0]);
print("The lenght of your full name is " (firstName + lastName).Length);
int Age = 2018 - birthYear;
print("Your age is :" + Age.ToString );
int dayAlive = Age * 365;
print("You lived: " dayAlive.ToString "days");
}
// Update is called once per frame
void Update()
{
}
This is a code I made following a tutorial (few simple problems to get an understanding of the basics)
And I keep getting these errors:
Severity Code Description Project File Line Suppression State
Error CS1003 Syntax error, ‘,’ expected Miscellaneous Files 14 Active
Error CS1003 Syntax error, ‘,’ expected Miscellaneous Files 19 Active
Error CS1003 Syntax error, ‘,’ expected Miscellaneous Files 19 Active
Can someone please help me??
aboba11235, ты скинул совсем не рабочий код. Это лишь одна из ошибок, которая ждала бы тебя в будущем.
Его даже исправить нельзя. Его нужно просто переделать. Я просто укажу на ошибки.
1) Почитай документацию к GUI.Label: https://docs.unity3d.com/Scrip… Label.html
2)
Сообщение от aboba11235
public GameObject Player;
public не нужен, если ты ищешь объект внутри этого же кода (строка 14)
3)
Сообщение от aboba11235
void OnColliderEnter (Collider other)
Такого метода нет. Есть OnCollisionEnter и его параметр должен быть типа Collision.
4)
Сообщение от aboba11235
if (Input.GetKeyDown(KeyCode.Mouse0))
Отработка нажатий должна вызываться каждый кадр, а метод OnCollisionEnter вызывается единожды при касании. (Скорее всего стоит заменить на OnCollisionStay)
5)
Сообщение от aboba11235
Player.GetComponent<Score>().Score += 10;
Ты назвал переменную так же, как и класс? Опрометчивое решение. Будут ошибки. Пофантазируй на эту тему.
6)
Сообщение от aboba11235
GUI.Label(new Rect(10, 10, 100, 100), «Score: » Score);
А теперь главная ошибка. И она вытекает из пункта 5. Компилятор думает, что ты пытаешься туда засунуть класс Score, а классы со строкой не совещаются, какое горе. Тебе нужна переменная Score в скрипте Score? Тогда обращайся к классу Score и его полю Score (согласно пункту 5 её стоит переименовать).
Если вдруг ещё останутся вопросы, задавай.
When uploading my game to Unity Distribution Portal (UDP), I kept on receiving this message about sandbox testing:
It seems your game was never tested in the UDP Sandbox environment, as no UDP Initialization call was found on the UDP back-end.
Launch your APK in the UDP Sandbox environment to ensure it initializes properly. You must complete this step to release your game.
Now, I initially thought that Unity sandbox testing was enabled as soon as you installed the UDP plugins, but I have read that you need to make a script like this for the testing procedures to pass:
using UnityEngine;
using UnityEngine.UDP;
public class InitListener : IInitListener
{
public void Initialize()
{
StoreService.Initialize(IInitListener listener);
}
public void OnInitialized(UserInfo userInfo)
{
Debug.Log("Initialization succeeded");
}
public void OnInitializeFailed(string message)
{
Debug.Log("Initialization failed: " + message);
}
}
However, I kept on encountering a syntax error that said
InitListener.cs(9,49): error CS1003: Syntax error, ‘,’ expected
…Even though there’s no need for a «,».
Typppi also suggested calling from another script to refer to this one, which I have made:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UDP;
public Script listener;
public class Initializer : MonoBehaviour
{
void Start()
{
StoreService.Initialize(IInitListener listener);
}
}
Yet it still returns the same syntax error. Even then, what am I supposed to do with this initialization script? Where do I assign it?
Thank you for reading.
I have just started unity and am very puzzled by the error that appears:
AssetsScriptsBird.cs(11,28): error CS1003: Syntax error, ',' expected
The AssetsScriptsBird.cs(11, 18) if my file name.
I have looked else where but all of the answers have not been relevant are the error seems really general. I’d imagen it is very obvious but I have only just started. Thanks
Sorry for not including the full code… but here it is now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bird : MonoBehaviour
{
[SerializeField] float _launchForce = 500;
Vector2 startPosition;
Rigidbody2D rigidbody2D:
SpriteRenderer spriteRenderer;
void Awake()
{
rigidbody2D = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
startPosition = rigidbody2D().position;
rigidbody2D().isKinematic = true;
}
void OnMouseDown()
{
spriteRenderer().color = new Color(1, 0, 0, 225);
}
void OnMouseUp()
{
spriteRenderer().color = new Color(1, 1, 1, 225);
Vector2 currentPosition = rigidbody2D().position;
Vector2 direction = startPosition - currentPosition;
direction.Normalize();
rigidbody2D().isKinematic = false;
rigidbody2D().AddForce(direction * _launchForce);
}
void OnMouseDrag()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(mousePosition.x, mousePosition.y, transform.position.z);
}
// Update is called once per frame
void Update()
{
}
}
SceneManager.LoadScene(SceneManager.GetActiveScene().name, LoadSceneMode.Single);
I don’t know Unity but Google tells me that works. Try and replace your line with that. You may be using an outdated tutorial.
From
https://forum.unity.com/threads/restart-a-scene-scenemanager-loadscene.430614/
.
In the future, please just copy the text and paste it here in a code block. A screen shot image pasted into a google drive document then shared, then pasted that link is a long way around.
I’ll transcribe three of the errors from that screen shot.
MainMenu.cs(10,59): error CS1001: Identifier expected
MainMenu.cs(10,59): error CS1003: Syntax error, “,” expected
Check line 59. There is probably a parameter missing. There might also be a semicolon missing at the end, or the compiler just got confused with the missing identifier.
LoadScene() has a mandatory parameter of the scene name, and an optional parameter of the mode. Check the spellings of everything.
MainMenu.cs(10,60): Error CS8124: Tuple must contain at least two elements.
Check line 60. This might be a carry-over from earlier errors, or from bigger structural errors. Possibly you have code that is outside of a function body, either because the compiler is struggling to recover from earlier errors, or because you misplaced some semicolons.
Repeat for the other errors. Line 61 and 62 are missing semicolons at the end, again either because they are actually missing or because of errors on earlier lines.
Lines 73 and 77 are missing other punctuation, but have similar issues.
ok sorry to sound dumb but i dont know what you mean on line 55 because there are not that many lines. ive only recently been taking a class on this and dont understand what that would mean.
Frob must have been in a rush.
(10,59) means there is an error around line 10, character 59. Double clicking on the first error should put your cursor very close to the problem.
Try my solution.
.
so how do I implement your solution?
@thecapl I’m not into repeating myself.
.
thecapl said:
so how do I implement your solution?
The instructions above are really pretty much literally what you have to do, but without you understanding them, there is no way for us to explain it to you.
What you need is more knowledge in the mechanics of writing code, understanding compiler output, and knowing how to fix those things in seconds to minutes(!). You can learn this by doing a few C# tutorials first before you try writing a game. Find a few C# tutorials, and write and debug small exercise programs, get some experience in writing code.
It may take a few weeks, but for making games it hardly makes a difference (it takes a lifetime anyway). It will make problems like the above trivial to fix, and you will understand much better what Unity code and its documentation is saying, it will make much more sense to you. That will speed up learning to make games a lot. As such, doing a few C# tutorials is a very good investment here.
thecapl said:
so how do I implement your solution?
Take this line out of your code…
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
and put in this line…
SceneManager.LoadScene(SceneManager.GetActiveScene().name, LoadSceneMode.Single);
This was my solution from earlier. Originally it took me several minutes to find this and post it. I don’t know if it works or not but for you to post “so how do I implement your solution?” is really lackluster.
.