Expected ошибка юнити

Hi everyone i’m new to Unity scripting and i cant deal with the problem please someone help me

here is the code:

using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

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

    }

program i’m using Microsoft Visual Studio

Thanks in advance!!!

Programmer's user avatar

Programmer

122k22 gold badges237 silver badges329 bronze badges

asked Aug 10, 2016 at 5:30

G.Czene's user avatar

You only missing } at the end of the script. The last } should close the class {. This was likely deleted by you by mistake. Sometimes, Unity does not recognize script change. If this problem is still there after making this modification, simply close and re-open Unity and Visual Studio/MonoDevelop.

using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

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

    }
}//<====This you missed.

answered Aug 10, 2016 at 5:35

Programmer's user avatar

ProgrammerProgrammer

122k22 gold badges237 silver badges329 bronze badges

0

Введение

Unity — это мощный игровой движок, который предоставляет возможность разработки разнообразных игр и виртуальных сред. Однако, при разработке проектов на Unity можно столкнуться с ошибками, которые могут вызвать затруднения в работе. В данной статье рассмотрены две типичные ошибки — CS1513 и CS1002, и представлены их решения.

Ошибка CS1513

Ошибка CS1513 » } expected» возникает, когда отсутствует закрывающая фигурная скобка в коде Unity. Эта ошибка указывает на то, что компилятор ожидает символа ‘}’, который закрывает блок кода.

Решение ошибки CS1513

Ключевым моментом решения ошибки CS1513 является обнаружение отсутствия закрывающей фигурной скобки. Для этого следует внимательно просмотреть код и убедиться, что каждая открывающая фигурная скобка имеет соответствующую закрывающую фигурную скобку. Если скобка не найдена, требуется добавить ее на соответствующем месте в коде.

Пример кода с ошибкой CS1513:

void Start()
{
    if (condition)
    {
        // some code
    // missing closing brace
// missing closing brace for Start() method

Код с исправлением ошибки CS1513:

void Start()
{
    if (condition)
    {
        // some code
    }
}

Ошибка CS1002

Ошибка CS1002 » ; expected» возникает, когда пропущена точка с запятой в коде Unity. Эта ошибка указывает на то, что компилятор ожидает символ ‘;’, который обозначает конец оператора.

Решение ошибки CS1002

Чтобы исправить ошибку CS1002, необходимо найти место, где пропущена точка с запятой, и добавить ее в соответствующем месте в коде.

Пример кода с ошибкой CS1002:

void Update()
{
    var speed = 10
    transform.Translate(speed * Time.deltaTime, 0, 0)
}

Код с исправлением ошибки CS1002:

void Update()
{
    var speed = 10;
    transform.Translate(speed * Time.deltaTime, 0, 0);
}

Заключение

Ошибки CS1513 и CS1002 могут возникать при разработке проектов на Unity, но они являются типичными и их исправление не представляет сложности. Важно правильно распознать причину ошибки и аккуратно внести необходимые исправления. Соблюдая правила написания кода и внимательно анализируя сообщения об ошибках, разработчики Unity смогут избежать этих проблем и сохранить свою продуктивность.

Перейти к контенту

C++ Error 1513-1514

Всем привет, я новичок как в Unity так и в C++.
Прошу вашей помощи, импортировал ассет на что Unity пожаловался на скрипт, многие ошибки устранил но вот две ошибки не получается, вот эти «error CS1514: { expected и error CS1513: } expected»
Вот сам скрипт:

Используется csharp

using UnityEngine;
using CharacterMotor;
public class CharacterMotor;
public class StepsHandlerExample : MonoBehaviour
{
    private CharacterMotor charMot;
    private Vector3 displacement;
    private float iniBackSpeed;
    private float iniForSpeed;
    private float iniSideSpeed;
    private Vector3 lastPos;
    private float slowBackSpeed;
    private float slowForSpeed;
    private float slowSideSpeed;
    public float slowWalkVolume = 0.1f;
    private bool onetime;
    public float normalWalkRate = 0.7f;
    public float slowWalkRate = 1.5f;

    private void Start()
    {
        lastPos = transform.position;
        charMot = GetComponent<CharacterMotor>();
        iniForSpeed = charMot.movement.maxForwardSpeed;
        iniBackSpeed = charMot.movement.maxBackwardsSpeed;
        iniSideSpeed = charMot.movement.maxSidewaysSpeed;

        slowBackSpeed = charMot.movement.maxBackwardsSpeed 6.0f;
        slowForSpeed = charMot.movement.maxForwardSpeed 7.0f;
        slowSideSpeed = charMot.movement.maxSidewaysSpeed 5.0f;

    }

    private void Update()
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            GetComponent<AudioSource>().volume = slowWalkVolume;
            charMot.movement.maxForwardSpeed = slowForSpeed;
            charMot.movement.maxBackwardsSpeed = slowBackSpeed;
            charMot.movement.maxSidewaysSpeed = slowSideSpeed;
            if (onetime)
            {
                onetime = false;
                CancelInvoke(«NormalWalk»);
                InvokeRepeating(«NormalWalk», 0f, slowWalkRate);
            }

        }
        else
        {
            GetComponent<AudioSource>().volume = 1f;
            charMot.movement.maxForwardSpeed = iniForSpeed;
            charMot.movement.maxBackwardsSpeed = iniBackSpeed;
            charMot.movement.maxSidewaysSpeed = iniSideSpeed;
            if (!onetime)
            {
                onetime = true;
                CancelInvoke(«NormalWalk»);
                InvokeRepeating(«NormalWalk», 0f, normalWalkRate);
            }

         
        }
    }

    private void NormalWalk()
    {
        displacement = transform.position lastPos;
        lastPos = transform.position;
        if (!charMot.IsJumping())
        {
            if (displacement.magnitude > 0.01)
            {
                if (!GetComponent<AudioSource>().isPlaying)
                {
                    GetComponent<AudioSource>().Play();
                }
            }
        }
    }

    private void OnGUI()
    {
        GUI.Box(new Rect(Screen.width/12, Screen.height (Screen.height/4), Screen.width/1.1f, Screen.height/5),
                  «Hold Left Shift to walk slowly without noise! see the difference if you run behind the enemy!»);
    }
}

Заранее всем спасибо большое.

Shram
UNец
 
Сообщения: 5
Зарегистрирован: 04 мар 2019, 14:02

Re: C++ Error 1513-1514

Сообщение 1max1 04 мар 2019, 15:16

Как насчет сходить уроки по с# почитать, глядишь сможешь отличать его от c++. К тому же, если ты и дальше планируешь развиваться, то код писать нужно в нормальной среде типа Visual Studio, которая будет подчеркивать строки с ошибками.
Что по твоему должна делать эта строка в твоем коде?

Используется csharp

public class CharacterMotor;

Конечно же ты не знаешь, потому что код-то не твой, ты его от куда-то взял в надежде на чудо, а разбираться не захотел :((

Аватара пользователя
1max1
Адепт
 
Сообщения: 5285
Зарегистрирован: 28 июн 2017, 10:51

Re: C++ Error 1513-1514

Сообщение Friend123 04 мар 2019, 17:09

1max1, улыбнул )))))

Аватара пользователя
Friend123
Старожил
 
Сообщения: 701
Зарегистрирован: 26 фев 2012, 22:12
Откуда: Тверь
  • ICQ

Re: C++ Error 1513-1514

Сообщение Shram 04 мар 2019, 18:32

1max1 писал(а):Как насчет сходить уроки по с# почитать, глядишь сможешь отличать его от c++. К тому же, если ты и дальше планируешь развиваться, то код писать нужно в нормальной среде типа Visual Studio, которая будет подчеркивать строки с ошибками.
Что по твоему должна делать эта строка в твоем коде?

Используется csharp

public class CharacterMotor;

Конечно же ты не знаешь, потому что код-то не твой, ты его от куда-то взял в надежде на чудо, а разбираться не захотел :((

Конечно не мой умник, читай внимательно ! Написано же что был импортирован ассет и было около 6-и ошибок, они ссылались на «CharacterMotor»
а когда я кидаю другой скрипт «CharacterMotor» тогда появдяется другая ошибка, «The type or namespace name ‘ParticleAnimator’ could not be found (are you missing a using directive or an assembly reference?»
Затем пришел к этим единственным ошибкам.
Но я вижу здесь все злые.

Shram
UNец
 
Сообщения: 5
Зарегистрирован: 04 мар 2019, 14:02

Re: C++ Error 1513-1514

Сообщение Friend123 04 мар 2019, 18:37

Shram писал(а):Но я вижу здесь все злые.

Это не мы злые, это вы, простите, задаете вопросы уровня 1 курса универа по программированию

Вот, если выдает ошибку, то в самой ошибке всегда сказано что не так, они все типовые. Простое гугление даст ответ в 10 раз быстрее, чем писать на форуме.

P.S. Как-то я думал всегда, что форумы для обсуждения сложных проблем. Ошибался видать.

Аватара пользователя
Friend123
Старожил
 
Сообщения: 701
Зарегистрирован: 26 фев 2012, 22:12
Откуда: Тверь
  • ICQ

Re: C++ Error 1513-1514

Сообщение Shram 04 мар 2019, 18:47

Friend123 писал(а):

Shram писал(а):Но я вижу здесь все злые.

Это не мы злые, это вы, простите, задаете вопросы уровня 1 курса универа по программированию

Вот, если выдает ошибку, то в самой ошибке всегда сказано что не так, они все типовые. Простое гугление даст ответ в 10 раз быстрее, чем писать на форуме.

P.S. Как-то я думал всегда, что форумы для обсуждения сложных проблем. Ошибался видать.

P.S. а я думал почемучка для этого и была создана.

Ну хорошо, смотрите я создал новый проект импортировал ассет, на что он мне ответил ошибкой вот такую

«StepsHandlerExample.cs(5,13): error CS0246: The type or namespace name ‘CharacterMotor’ could not be found (are you missing a using directive or an assembly reference?»

И поверьте я пользовался «Google» проверил имя скрипта «CharacterMotor» совпадает, Google не чего не нашел.

Shram
UNец
 
Сообщения: 5
Зарегистрирован: 04 мар 2019, 14:02

Re: C++ Error 1513-1514

Сообщение 1max1 04 мар 2019, 19:40

Похоже автор твоего ассета забыл добавить скрипт CharacterMotor))

И поверьте я пользовался «Google» проверил имя скрипта «CharacterMotor» совпадает, Google не чего не нашел.

Что-то я тебе не верю)))

http://wiki.unity3d.com/index.php/CharacterMotor

Аватара пользователя
1max1
Адепт
 
Сообщения: 5285
Зарегистрирован: 28 июн 2017, 10:51

Re: C++ Error 1513-1514

Сообщение Shram 04 мар 2019, 19:57

1max1 писал(а):Похоже автор твоего ассета забыл добавить скрипт CharacterMotor))

И поверьте я пользовался «Google» проверил имя скрипта «CharacterMotor» совпадает, Google не чего не нашел.

Что-то я тебе не верю)))

http://wiki.unity3d.com/index.php/CharacterMotor

Этот скрипт я находил и добавлял, но все же спасибо, но теперь вылезли еще ошибки, суть их схожая

«The type or namespace name ‘ParticleAnimator’ could not be found (are you missing a using directive or an assembly reference?»

Теперь я понял что значит Не удалось найти ссылка на сборку, нет тупа скрипта, я ведь правельно все понял ? Значит уже два скрипта он забыл положить ?

Shram
UNец
 
Сообщения: 5
Зарегистрирован: 04 мар 2019, 14:02


Re: C++ Error 1513-1514

Сообщение Shram 04 мар 2019, 20:36

Ну да точно, ассет требует версию 4.6 теперь все понял.
Спасибо большое, вот теперь есть не большой как в скриптах так и в юнити.

Shram
UNец
 
Сообщения: 5
Зарегистрирован: 04 мар 2019, 14:02


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

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

Сейчас этот форум просматривают: Google [Bot] и гости: 31

Hi everyone i’m new to Unity scripting and i cant deal with the problem please someone help me

here is the code:

using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

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

    }

program i’m using Microsoft Visual Studio

Thanks in advance!!!

Programmer's user avatar

Programmer

119k21 gold badges231 silver badges318 bronze badges

asked Aug 10, 2016 at 5:30

G.Czene's user avatar

You only missing } at the end of the script. The last } should close the class {. This was likely deleted by you by mistake. Sometimes, Unity does not recognize script change. If this problem is still there after making this modification, simply close and re-open Unity and Visual Studio/MonoDevelop.

using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

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

    }
}//<====This you missed.

answered Aug 10, 2016 at 5:35

Programmer's user avatar

ProgrammerProgrammer

119k21 gold badges231 silver badges318 bronze badges

0

StAsIk2008

0 / 0 / 0

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

Сообщений: 1

1

20.02.2020, 13:09. Показов 12911. Ответов 3

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


вот скрипт

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using UnityEngine;
using System.Collections;
 
[RequireComponent(typeof(Rigidbody2D))]
 
public class Player2DControl : MonoBehaviour
{
 
    public enum ProjectAxis { onlyX = 0, xAndY = 1 };
    public ProjectAxis projectAxis = ProjectAxis.onlyX;
    public float speed = 150;
    public float addForce = 7;
    public bool lookAtCursor;
    public KeyCode leftButton = KeyCode.A;
    public KeyCode rightButton = KeyCode.D;
    public KeyCode upButton = KeyCode.W;
    public KeyCode downButton = KeyCode.S;
    public KeyCode addForceButton = KeyCode.Space;
    public bool isFacingRight = true;
    private Vector3 direction;
    private float vertical;
    private float horizontal;
    private Rigidbody2D body;
    private float rotationY;
    private bool jump;
 
    void Start()
    {
        body = GetComponent<Rigidbody2D>();
        body.fixedAngle = true;
 
        if (projectAxis == ProjectAxis.xAndY)
        {
            body.gravityScale = 0;
            body.drag = 10;
        }
    }
 
    void OnCollisionStay2D(Collision2D coll)
    {
        if (coll.transform.tag == "Ground")
        {
            body.drag = 10;
            jump = true;
        }
    }
 
    void OnCollisionExit2D(Collision2D coll)
    {
        if (coll.transform.tag == "Ground")
        {
            body.drag = 0;
            jump = false;
        }
    }
 
    void FixedUpdate()
    {
        body.AddForce(direction * body.mass * speed);
 
        if (Mathf.Abs(body.velocity.x) > speed / 100f)
        {
            body.velocity = new Vector2(Mathf.Sign(body.velocity.x) * speed / 100f, body.velocity.y);
        }
 
        if (projectAxis == ProjectAxis.xAndY)
        {
            if (Mathf.Abs(body.velocity.y) > speed / 100f)
            {
                body.velocity = new Vector2(body.velocity.x, Mathf.Sign(body.velocity.y) * speed / 100f);
            }
        }
        else
        {
            if (Input.GetKey(addForceButton) && jump)
            {
                body.velocity = new Vector2(0, addForce);
            }
        }
    }
 
    void Flip()
    {
        if (projectAxis == ProjectAxis.onlyX)
        {
            isFacingRight = !isFacingRight;
            Vector3 theScale = transform.localScale;
            theScale.x *= -1;
            transform.localScale = theScale;
        }
    }
 
    void Update()
    {
        if (lookAtCursor)
        {
            Vector3 lookPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
            lookPos = lookPos - transform.position;
            float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        }
 
        if (Input.GetKey(upButton)) vertical = 1;
        else if (Input.GetKey(downButton)) vertical = -1; else vertical = 0;
 
        if (Input.GetKey(leftButton)) horizontal = -1;
        else if (Input.GetKey(rightButton)) horizontal = 1; else horizontal = 0;
 
        if (projectAxis == ProjectAxis.onlyX)
        {
            direction = new Vector2(horizontal, 0);
        }
        else
        {
            if (Input.GetKeyDown(addForceButton)) speed += addForce; else if (Input.GetKeyUp(addForceButton)) speed -= addForce;
            direction = new Vector2(horizontal, vertical);
        }
 
        if (horizontal > 0 && !isFacingRight) Flip(); else if (horizontal < 0 && isFacingRight) Flip();

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

0

управление сложностью

1687 / 1300 / 259

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

Сообщений: 7,545

Записей в блоге: 5

20.02.2020, 13:38

2

Пропущена закрывающая скобка, либо лишняя открывающая

0

11 / 9 / 8

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

Сообщений: 139

20.02.2020, 14:55

3

На какую строку ругается?

0

0 / 0 / 0

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

Сообщений: 87

24.02.2020, 11:53

4

В конец поставь знак }

0

I was programming (C#) a day/night cycle system for my unity game when I got the following error:
AssetsScriptsRotate.cs(15,6): error CS1513: } expected

My code should calculate a ‘time’ in minutes from the rotation of the sun (Which is attached to this object).

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Rotate : MonoBehaviour
{
public float timescale=1f;
private int hour=12;
private int minute=0;
void Start()
{
StartCoroutine("TickUpdate");
}
public IEnumerator TickUpdate()
{
private string stringbuffer1;
for(;;)
{
private float RotationSpeed 0.0025*timescale
gameObject.transform.Rotate(RotationSpeed,0f,0f);
public float RawMinute=0.00694444444444444444444444444444f*(gameObject.transform.rotation.x-90);
public string time="{hour}:{minute}";
yield return new WaitForSeconds(.01f);
}
}
}

I already checked multiple sites and the unity answers form.
Any help would be appericiated.

(I’m using Notepad++ as my editor)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerMovementTutorial : MonoBehaviour
{
[Header("Movement")]
public float moveSpeed;
public float groundDrag;
public float jumpForce;
public float jumpCooldown;
public float airMultiplier;
bool readyToJump;
[HideInInspector] public float walkSpeed;
[HideInInspector] public float sprintSpeed;
[Header("Keybinds")]
public KeyCode jumpKey = KeyCode.Space;
[Header("Ground Check")]
public float playerHeight;
public LayerMask whatIsGround;
bool grounded;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
readyToJump = true;
}
private void Update()
{
// ground check
grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.3f, whatIsGround);
MyInput();
SpeedControl();
// handle drag
if (grounded)
rb.drag = groundDrag;
else
rb.drag = 0;
}
private void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
// when to jump
if(Input.GetKey(jumpKey) && readyToJump && grounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
}
private void MovePlayer()
{
// calculate movement direction
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
// on ground
if(grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
// in air
else if(!grounded)
rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
// limit velocity if needed
if(flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
private void Jump()
{
// reset y velocity
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
readyToJump = true;
}

Skip to content

I have a little problem with my C# code, so I have this simple PlayerHealth code here and Unity always gives me this error: Unity Bracket Error

Code:

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

public class PlayerHealth : MonoBehaviour
{
    public float health = 100;
    public float damage = 10;


    void OnCollisionEnter(otherObj Collision) {
        if (otherObj.tag == "Bullet") {
            health = health - damage;
            if (health < 0)
            {
                Destroy(gameObject);
            }
        }
    }
}

I appreciate your help! 😀

>Solution :

Check your OnCollisionEnter function, the parameter is wrong.

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

public class PlayerHealth : MonoBehaviour
{
    public float health = 100f;
    public float damage = 10f;

    void OnCollisionEnter(Collision otherObj) 
    {
        if (otherObj.gameObject.tag == "Bullet") 
        {
            health = health - damage;
            if (health < 0)
            {
                Destroy(gameObject);
            }
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Expected the beginning of a construct clips ошибка
  • Expected sub function or property ошибка
  • Expected string or bytes like object python ошибка
  • Expected list separator or ошибка
  • F00316 ошибка рено