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

StAsIk2008

0 / 0 / 0

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

Сообщений: 1

1

20.02.2020, 13:09. Показов 14769. Ответов 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



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

121k22 gold badges234 silver badges324 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

121k22 gold badges234 silver badges324 bronze badges

0

This is a common error that coders can get on a regular basis. This is a compiler error because you receive this error prior to playing your game. There are a number of scenarios that can trigger this error but the most common ways to receive this error is by the following.

  1. Having the wrong number of closing symbols for your functions and classes. These include ), ], and }.
  2. Forgetting the semicolon(;) at the end of a line of code.
  3. Placing operators(+, -, *, /, <, >, =) where they don’t belong.

in addition to these common ways of triggering an Unexpected symbol error, this error can be caused by any character out of place.

I have an error that I cannot figure out in Unity.

What this does (I think) is move a platform to and from points.

I have just put some text here so I can actually post this… why does stack overflow do this.

Here’s the error:

AssetsScriptsMover.cs(74,1): error CS1022: Type or namespace definition, or end-of-file expected

Here’s the code:

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

public class Mover : MonoBehaviour {

  public Vector3[] points;
  public int point_number = 0;
  private Vector3 current_target;

  public float tolerance;
  public float speed;
  public float delay_time;

  private float delay_start;

  public bool automatic;


    // Start is called before the first frame update
    void Start()
    {
         if(points.lengh > 0)
         {
           current_target = 0;
         }
         time = speed * Time.deltaTime;
       }
    }

    // Update is called once per frame
    void Update()
    {
        if(transform.position != current_target)
        {
           MovePlatform();
        }
        else
        {
            UpdateTarget();
        }
    }

    void  MovePlatform()
    {
      Vector3 heading = current_target - transform.position;
      transform.position += (heading / heading.magnitude) * speed * time.deltaTime;
       if(heading.magnitude = tolerance)
       {
        transform.position = current_target;
        delay_start = Time.time;
       }
    }
    void UpdateTarget()
    {
      if(automatic)
      {
          if(Time.time - delay_start > delay_time)
          {
           NextPlatform();
          }
       }
    }
    public void NextPlatform()
    {
        point_number ++;
        if(point_number >= points.Length)
        {
          point_number = 0;
        }
        current_target = points[point_number];
    }
}

pinkfloydx33's user avatar

pinkfloydx33

11.3k3 gold badges43 silver badges60 bronze badges

asked May 24, 2020 at 3:19

NickKnack's user avatar

It looks like you have an extra curley in your start function that is messing with your code

 void Start()
    {
         if(points.lengh > 0)
         {
            current_target = 0;
         }
         time = speed * Time.deltaTime;
       }
    }

— remove last curley

answered May 24, 2020 at 3:33

vasmos's user avatar

vasmosvasmos

2,4521 gold badge10 silver badges21 bronze badges

You have a some basic mistakes:

  1. You are not defining your class inside a namespace.
  2. Your methods from Update() to the last one are defined outside of your class scope (closing curly bracket of your class is located before Update().

I cannot check if the types you are using are defined somewhere or not.

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

namespace ConsoleApp
{
    public class Mover
    {
        private Vector3 current_target;
        private float delay_start;

        public Vector3[] points;
        public int point_number = 0;
        public float tolerance;
        public float speed;
        public float delay_time;
        public bool automatic;

        // Start is called before the first frame update
        void Start()
        {
            if (points.lengh > 0)
            {
                current_target = 0;
            }
            time = speed * Time.deltaTime;
        }

        // Update is called once per frame
        void Update()
        {
            if (transform.position != current_target)
            {
                MovePlatform();
            }
            else
            {
                UpdateTarget();
            }
        }

        void MovePlatform()
        {
            Vector3 heading = current_target - transform.position;
            transform.position += (heading / heading.magnitude) * speed * time.deltaTime;
            if (heading.magnitude = tolerance)
            {
                transform.position = current_target;
                delay_start = Time.time;
            }
        }
        void UpdateTarget()
        {
            if (automatic)
            {
                if (Time.time - delay_start > delay_time)
                {
                    NextPlatform();
                }
            }
        }
        public void NextPlatform()
        {
            point_number++;
            if (point_number >= points.Length)
            {
                point_number = 0;
            }
            current_target = points[point_number];
        }
    }
}

answered May 24, 2020 at 3:35

Cfun's user avatar

CfunCfun

7,9414 gold badges27 silver badges60 bronze badges

1

the time Variable isn’t exist

the magnitude Property is read-only (It means you can’t set any value on magnitude)

the type of current_target is Vector3 so u need to set values that their Types are Vector3

there is no Property exist for Vector3 variables that called length

looks like you are missing one of the Brackets in the code or write wrong

answered May 24, 2020 at 5:37

mohammadhosseinborhani's user avatar

Содержание

  1. error CS1022: Type or namespace definition, or end-of-file expected
  2. Error CS1022: Type or namespace definition, or end-of-file expected in unity [closed]
  3. 3 Answers 3
  4. Unity gives «Type or namespace definition, or end-of-file expected» error
  5. 1 Answer 1
  6. AssetsScriptsInGamePanel.cs(6,1): error CS1022: Type or namespace definition, or end-of-file expected
  7. 1 Answer 1
  8. Related
  9. Hot Network Questions
  10. Subscribe to RSS
  11. Error CS1022: Type or namespace definition, or end-of-file expected in unity [closed]
  12. 3 Answers 3

error CS1022: Type or namespace definition, or end-of-file expected

I’m creating a messaging application for andriod/ios, but I am completely new to c# and networking, I’ve followed the first steps of a simple socket tutorial to get me started in networking (https://www.youtube.com/watch?v=KxdOOk6d_I0) but I get the error:

error «CS1022: Type or namespace definition, or end-of-file expected».

I’m assuming that it has something to do with the namespace because im new to c# and don’t actually understand what the namespace does, but my compiler says there are no errors (I’m using visual studio code if that makes a difference) but it may be something else.

it should say server started. » or throw up an exeption but this is what im getting every time:

[Running] mono «C:UsersAidanAppDataRoamingCodeUsercs-script.usercscs.exe» «d:!computer science!!NEA!test stuffnetworkingserver_testprogram.cs» Error: Specified file could not be compiled.

csscript.CompilerException: d:!computer science!!NEA!test stuffnetworkingserver_testprogram.cs(7,127): error CS1513: > expected d:!computer science!!NEA!test stuffnetworkingserver_testprogram.cs(37,1): error CS1022: Type or namespace definition, or end-of-file expected

at csscript.CSExecutor.ProcessCompilingResult (System.CodeDom.Compiler.CompilerResults results, System.CodeDom.Compiler.CompilerParameters compilerParams, CSScriptLibrary.ScriptParser parser, System.String scriptFileName, System.String assemblyFileName, System.String[] additionalDependencies) [0x00102] in :0 at csscript.CSExecutor.Compile (System.String scriptFileName) [0x0080d] in :0 at csscript.CSExecutor.ExecuteImpl () [0x005a1] in :0

[Done] exited with code=1 in 1.795 seconds

Источник

Error CS1022: Type or namespace definition, or end-of-file expected in unity [closed]

Closed 2 years ago .

I have an error that I cannot figure out in Unity.

What this does (I think) is move a platform to and from points.

I have just put some text here so I can actually post this. why does stack overflow do this.

Here’s the error:

AssetsScriptsMover.cs(74,1): error CS1022: Type or namespace definition, or end-of-file expected

3 Answers 3

It looks like you have an extra curley in your start function that is messing with your code

— remove last curley

You have a some basic mistakes:

  1. You are not defining your class inside a namespace.
  2. Your methods from Update() to the last one are defined outside of your class scope (closing curly bracket of your class is located before Update() .

I cannot check if the types you are using are defined somewhere or not.

the time Variable isn’t exist

the magnitude Property is read-only (It means you can’t set any value on magnitude)

the type of current_target is Vector3 so u need to set values that their Types are Vector3

there is no Property exist for Vector3 variables that called length

looks like you are missing one of the Brackets in the code or write wrong

Источник

Unity gives «Type or namespace definition, or end-of-file expected» error

Getting two errors here, but I’m pretty sure they’re dependent upon each other:

AssetsCourse LibraryScriptsPlayerController.cs(9,16): error CS1513: > expected

AssetsCourse LibraryScriptsPlayerController.cs(42,1): error CS1022: Type or namespace definition, or end-of-file expected

It doesn’t really make any sense to me. I’m certain I formatted it correctly, and that the syntax is correct. Anytime I make any changes to the line of code where the errors are, it only throws more errors at me.

I thought there was a possibility that there was only one mistake somewhere in the code that causing a compound reaction, but I couldn’t find anything wrong.

Could someone with more knowledge about Unity please explain to me what it is I’m doing wrong?

1 Answer 1

In general: It is very unlikely that a compiler is broken in a way that it throws this kind of exception 😉

In Start you do

You can not define a public field within the Start method (or any method in general to be exact).

Thus, before the public keyword the compiler expects a > to close the Start method. The rest is just follow-up errors caused by this first one.

The compiler will try to continue and «assume» the > was where it expects it thus your class PlayerController would already be closed with the next > after public float tank . so the next error appears when hitting public float horizontalInput since it would require a class / struct around it. Therefore you a

Type or namespace definition, or end-of-file expected

Источник

AssetsScriptsInGamePanel.cs(6,1): error CS1022: Type or namespace definition, or end-of-file expected

hi i get this errors using unity 1 ==> AssetsScriptsInGamePanel.cs(6,1): error CS1022: Type or namespace definition, or end-of-file expected

2 ==> AssetsScriptsInGamePanel.cs(110,1): error CS1022: Type or namespace definition, or end-of-file expected

please any help for this issue i get this problem for many times

1 Answer 1

You cannot code methods in the global namespace directly. These need to go inside a class. If you want Start() and Update() you need it to derive from monobehaviour. Put your code inside this trial class and name it as you wish. Remember the name of the script should be the same of the class with .cs, for this class for example should be TrialClass.cs, so that you can attach scripts to gameobjects.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Error CS1022: Type or namespace definition, or end-of-file expected in unity [closed]

Closed 2 years ago .

I have an error that I cannot figure out in Unity.

What this does (I think) is move a platform to and from points.

I have just put some text here so I can actually post this. why does stack overflow do this.

Here’s the error:

AssetsScriptsMover.cs(74,1): error CS1022: Type or namespace definition, or end-of-file expected

3 Answers 3

It looks like you have an extra curley in your start function that is messing with your code

— remove last curley

You have a some basic mistakes:

  1. You are not defining your class inside a namespace.
  2. Your methods from Update() to the last one are defined outside of your class scope (closing curly bracket of your class is located before Update() .

I cannot check if the types you are using are defined somewhere or not.

the time Variable isn’t exist

the magnitude Property is read-only (It means you can’t set any value on magnitude)

the type of current_target is Vector3 so u need to set values that their Types are Vector3

there is no Property exist for Vector3 variables that called length

looks like you are missing one of the Brackets in the code or write wrong

Источник

In C#, all executable code is contained in methods: only variable and class definitions can be outside — and variables need to be within a class.

So your if code needs to be inside a method to be effective:

private float myFloat = 0.0f;
public void myMethod(float myParameter)
   {
   if (myParameter == 666.0f)
      {
      ...
      }
   }

And although #if exists, it doesn’t get executed when your code is running — it’s a directive to the compiler to include or exclude code when you build the EXE file, not included in the EXE for later execution.

If you think of it like a car, when your buy a new car you select the options you want on it: black paint, 20″ rims, and Cruise control for you! That provides directives to the car manufacturer when they build it:

#if (paint == Black) PaintIt(Black)
#elseif (paint = Red) PaintIt(Red)
#else PaintIt(White);

That «fixes the options» on the car, they don’t change from that point on and when delivered to you it will be black, sit higher, and have an extra stick on the steering column. You can use the cruise control at any time while you drive it, but unless you selected it with #if when you bought the car, it doesn’t exist and you can’t use it.

#if in C# code, does the same thing: selects what code is comp0iled and stored into the EXE you run later. if is used to make decisions when the EXE file is running and you are playing the game, reading data from a DB, or shatever you app is trying to do.

ошибка

ошибка

Добрый день. Не могу понять в чем ошибка в коде. Заранее спасибо!

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

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

public class WWW : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        public Slider qlider;
    }

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

       
    }
}

ошибка
1)AssetsWWW.cs(19,1): error CS1022: Type or namespace definition, or end-of-file expected
2)AssetsWWW.cs(10,6): error CS1513: } expected

Последний раз редактировалось SDSS_Spai 26 май 2020, 01:29, всего редактировалось 2 раз(а).

SDSS_Spai
UNец
 
Сообщения: 3
Зарегистрирован: 26 май 2020, 00:39

Re: ошибка

Сообщение Alex5 26 май 2020, 01:05

Вообще, код лучше давать кодом, а не картинкой. Если сходу — класс и переменная не должны быть одинаковыми. Я про

Код: Выделить всё
public Slider Slider;
Аватара пользователя
Alex5
Старожил
 
Сообщения: 507
Зарегистрирован: 22 авг 2019, 17:37

Re: ошибка

Сообщение SDSS_Spai 26 май 2020, 01:25

1)Хорошо
2)Не помогло.

SDSS_Spai
UNец
 
Сообщения: 3
Зарегистрирован: 26 май 2020, 00:39

Re: ошибка

Сообщение Alex5 26 май 2020, 01:37

А ошибки те же? Ну и лучше, наверное, переменную определять в теле класса, а не в его методе Start.
Т.е.

Код: Выделить всё
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class NewBehaviourScript : MonoBehaviour
{
    public Slider qlider;

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

    }

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

           }
}

Последний раз редактировалось Alex5 26 май 2020, 02:18, всего редактировалось 1 раз.

Аватара пользователя
Alex5
Старожил
 
Сообщения: 507
Зарегистрирован: 22 авг 2019, 17:37

Re: ошибка

Сообщение Alex5 26 май 2020, 01:39

А еще лучше уважать советующих. Они ведь не обязаны угадывать текст и ошибки по картинке.

Аватара пользователя
Alex5
Старожил
 
Сообщения: 507
Зарегистрирован: 22 авг 2019, 17:37

Re: ошибка

Сообщение SDSS_Spai 26 май 2020, 02:00

Да точно, спасибо. Не внимателен.
Извиняюсь.

SDSS_Spai
UNец
 
Сообщения: 3
Зарегистрирован: 26 май 2020, 00:39


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

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

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

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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using Random = UnityEngine.Random;
 
 
[RequireComponent(typeof(Rigidbody))]
public class CarController : MonoBehaviour 
{ 
    public bool rightTurn, leftTurn, moveFromUp;
    public float speed = 15f, force =50f;
    private Rigidbody carRb; 
    private float rotateMultRight = 6f, rotateMultLeft = 4.5f, originRotationY;
    private Camera mainCam;  
    public LayerMask carsLayer; 
    private bool isMovingFast; 
    [NonSerialized] public bool carPassed;
    public GameObject turnLeftSignal, turnRightSignal, explosion, exhaust;
    [NonSerialized] public static bool isLose;
    [NonSerialized] public static int countCars;
    public AudioClip crash;  
    public AudioClip[] accelerator;
 
    private void Start()  
    {
        mainCam = Camera.main;
        carRb = GetComponent<Rigidbody>();
        originRotationY = transform.eulerAngles.y; 
 
        if (rightTurn)
            StartCoroutine(TurnSignals(turnRightSignal));
        else if (leftTurn)
            StartCoroutine(TurnSignals(turnLeftSignal));
    } 
 
 
 
    IEnumerator TurnSignals(GameObject turnSignal)
    {
        while (!carPassed)
        {
            turnSignal.SetActive(!turnSignal.activeSelf);
            yield return new WaitForSeconds(0.5f);
        }
    }
 
    private void Update()
    {
 #if UNITY_EDITOR
        Ray ray = mainCam.ScreenPointToRay(Input.mousePosition);
 
 #else
        if (Input.touchCount == 0)
            return;
        Ray ray = mainCam.ScreenPointToRay(Input.GetTouch(0).position);
 #endif 
        RaycastHit hit;
 
        if (Physics.Raycast(ray, out hit, maxDistance: 100f, carsLayer))
        {
            string carName = hit.transform.gameObject.name;
 #if UNITY_EDITOR
            if (Input.GetMouseButtonDown(0) && !isMovingFast && gameObject.name == carName)
            {
 #else
            if (Input.GetTouch(0).phase == TouchPhase.Began && !isMovingFast && gameObject.name == carName)
 #endif
            {
                GameObject vfx = Instantiate(exhaust, new Vector3(transform.position.x, transform.position.y + 1.5f, transform.position.z), Quaternion.Euler(90, 0, 0)) as GameObject;
                Destroy(vfx, 2f);
                speed *= 2.5f;
                isMovingFast = true;
            }
 
           if (PlayerPrefs.GetString("music") != "No")
            {
                GetComponent<AudioSource>().clip = accelerator[Random.Range(0, accelerator.Length)];
                GetComponent<AudioSource>().Play();
            }
 
            }
        } 
    }
 
    private void FixedUpdate()
    {
        carRb.MovePosition(transform.position - transform.forward * speed * Time.fixedDeltaTime);
    }
 
    private void OnCollisionEnter(Collision other)
    {
      if (other.gameObject.CompareTag("Car"))
      {
        isLose = true;
        speed = 0f;
        other.gameObject.GetComponent<CarController>().speed = 0f;
        GameObject vfx = Instantiate(explosion, transform.position, Quaternion.identity) as GameObject;
        Destroy(vfx, 4f);
 
        if (isMovingFast)
            force *= 1.2f;
 
        carRb.AddRelativeForce(Vector3.back * force); 
 
        if (PlayerPrefs.GetString("music") != "No")
        {
            GetComponent<AudioSource>().clip = crash;
            GetComponent<AudioSource>().Play();
        }
      }
    }
 
 
 
    private void OnTriggerEnter(Collider other)
    {
         if (other.gameObject.CompareTag("Car") && other.GetComponent<CarController>().carPassed)
 
         other.GetComponent<CarController>().speed = speed;
 
    }
 
    private void OnTriggerStay(Collider other)
    {
         if (isLose)
        return;
        if (other.transform.CompareTag("TurnBlock Right") && rightTurn)
        {
            RotateCar(rotateMultRight);
        }
        else if(other.transform.CompareTag("TurnBlock Left") && leftTurn)
        {
            RotateCar(rotateMultLeft,  -1);
        }
 
    }
 
    private void OnTriggerExit(Collider other)
    {
        if (other.transform.CompareTag("Trigger Pass"))
    {   if (carPassed)
            return;
        carPassed = true;
        Collider[] colliders = GetComponents<BoxCollider>();
        foreach (Collider col in colliders)
            col.enabled = true;
        countCars++;
    }
        if (other.transform.CompareTag("TurnBlock Right") && rightTurn)
            carRb.rotation = Quaternion.Euler(0, originRotationY + 90f, 0);
        else if (other.transform.CompareTag("TurnBlock Left") && leftTurn)
            carRb.rotation = Quaternion.Euler(0, originRotationY - 90f, 0);
        else if (other.transform.CompareTag("DestroyCars"))
 
            Destroy(gameObject);
    }
 
    private void RotateCar(float speedRotate, int dir = 1)
 
    {          if (isLose)
                 return; 
 
    if (dir == -1 && transform.localRotation.eulerAngles.y < originRotationY - 90f)
            return;
                if (dir == -1 && moveFromUp && transform.localRotation.eulerAngles.y > 250f && dir == -1 && transform.localRotation.eulerAngles.y < 270f)
            return;
                float rotateSpeed = speed * speedRotate * dir;
                Quaternion deltaRotation = Quaternion.Euler(new Vector3(0, rotateSpeed* Time.fixedDeltaTime, 0) );
                carRb.MoveRotation(carRb.rotation * deltaRotation);
    }
}
 
 
2)using System;
using UnityEngine;
using GoogleMobileAds.Api;
 
public class AdssManager : MonoBehaviour
{
 
 
#if UNITY_EDITOR
    string adUnitId = "ca-app-pub-7216743424948383/4317969368";
#elif UNITY_ANDROID
    string adUnitId = "unexpected_platform";
#elif UNITY_IPHONE
        string adUnitId = "unexpected_platform";
#else
    string adUnitId = "unexpected_platform";
#endif
        private InterstitialAd interstitial;
            private int nowLoses;
 
    private void Start()
    {
        DontDestroyOnLoad(gameObject);
 
        DestroyAndStartNew(true);
    }
 
    private void Update()
    {
        if (interstitial.IsLoaded() && GameController.countLoses % 3 == 0 && GameController.countLoses != 0 && GameController.countLoses != nowLoses)
        {
            nowLoses = GameController.countLoses;
            interstitial.Show();
        }
    }
 
    public void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
    {
        DestroyAndStartNew();
    }
 
    public void HandleOnAdClosed(object sender, EventArgs args)
    {
        DestroyAndStartNew();
    }
 
    public void HandleOnAdLeavingApplication(object sender, EventArgs args)
    {
        DestroyAndStartNew();
    }
 
    void DestroyAndStartNew(bool isFirst = false)
    {
        if (!isFirst)
            interstitial.Destroy();
 
        interstitial = new InterstitialAd(adUnitId);
        // Called when an ad request failed to load.
        this.interstitial.OnAdFailedToLoad += HandleOnAdFailedToLoad;
        // Called when the ad is closed.
        this.interstitial.OnAdClosed += HandleOnAdClosed;
        // Called when the ad click caused the user to leave the application.
        //this.interstitial.OnAdLeavingApplication += HandleOnAdLeavingApplication;
        AdRequest request = new AdRequest.Builder().Build();
        // Load the interstitial with the request.
        this.interstitial.LoadAd(request);
    }
}
 
 
 
3)using System;
using UnityEngine;
using UnityEngine.Purchasing;
 
public class IAPPManager : MonoBehaviour, IStoreListener
{
 
    public static IAPPManager instance;
 
    private static IStoreController m_StoreController;
    private static IExtensionProvider m_StoreExtensionProvider;
 
    private const string REMOVE_ADS = "remove_ads";
    private const string OPEN_CITY = "open_city";
    private const string OPEN_MEGAPOLIS = "open_megapolis";
 
    public void InitializePurchasing()
    {
        if (IsInitialized()) return;
        var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
 
        builder.AddProduct(REMOVE_ADS, ProductType.NonConsumable);
        builder.AddProduct(OPEN_CITY, ProductType.NonConsumable);
        builder.AddProduct(OPEN_MEGAPOLIS, ProductType.NonConsumable);
 
        UnityPurchasing.Initialize(this, builder);
    }
 
    private bool IsInitialized()
    {
        return m_StoreController != null && m_StoreExtensionProvider != null;
    }
 
    public void BuyNoAds()
    {
        BuyProductID(REMOVE_ADS);
    }
 
    public void BuyCityMap()
    {
        BuyProductID(OPEN_CITY);
    }
 
    public void BuyMegapolisMap()
    {
        BuyProductID(OPEN_MEGAPOLIS);
    }
 
    public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
    {
        if (String.Equals(args.purchasedProduct.definition.id, REMOVE_ADS, StringComparison.Ordinal))
        {
            // Товар был куплен успешно, можно его отдать пользователю
            PlayerPrefs.SetString("NoAds", "yes");
            Destroy(GameObject.Find("Ad"));
            //Destroy(GameObject.Find("noadsbutton"));
        }
        else if (String.Equals(args.purchasedProduct.definition.id, OPEN_CITY, StringComparison.Ordinal))
        {
            PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") +1000);
            GameObject shopCntrl = GameObject.Find("ShopController");
            shopCntrl.GetComponent<BuyCoinMap>().BuyNewMap(1000);
        }
        else if (String.Equals(args.purchasedProduct.definition.id, OPEN_MEGAPOLIS, StringComparison.Ordinal))
        {
            PlayerPrefs.SetInt("Coins", PlayerPrefs.GetInt("Coins") + 5000);
            GameObject shopCntrl = GameObject.Find("ShopController");
            shopCntrl.GetComponent<BuyCoinMap>().BuyNewMap(5000);
        }
        else
        {
            // Неуспешный платеж
        }
        return PurchaseProcessingResult.Complete;
    }
 
 
    private void Awake()
    {
        TestSingleton();
    }
 
    void Start()
    {
        if (m_StoreController == null) InitializePurchasing();
    }
 
    private void TestSingleton()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            return;
        }
 
        instance = this;
        DontDestroyOnLoad(gameObject);
    }
 
    void BuyProductID(string productId)
    {
        if (IsInitialized())
        {
            Product product = m_StoreController.products.WithID(productId);
            if (product != null && product.availableToPurchase)
            {
                Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
                m_StoreController.InitiatePurchase(product);
            }
            else
                Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
        }
        else
        {
            Debug.Log("BuyProductID FAIL. Not initialized.");
        }
    }
 
    public void RestorePurchases()
    {
        if (!IsInitialized())
        {
            Debug.Log("RestorePurchases FAIL. Not initialized.");
            return;
        }
 
        if (Application.platform == RuntimePlatform.IPhonePlayer ||
            Application.platform == RuntimePlatform.OSXPlayer)
        {
            Debug.Log("RestorePurchases started ...");
 
            var apple = m_StoreExtensionProvider.GetExtension<IAppleExtensions>();
            apple.RestoreTransactions((result) => {
                Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
            });
        }
        else
        {
            Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
        }
    }
 
    public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
    {
        Debug.Log("OnInitialized: PASS");
        m_StoreController = controller;
        m_StoreExtensionProvider = extensions;
    }
 
 
    public void OnInitializeFailed(InitializationFailureReason error)
    {
        Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
    }
 
    public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
    {
        Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
    }
}

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);
            }
        }
    }
}

Like this post? Please share to your friends:
  • External ошибка драйвера
  • Extension timeout error ошибка
  • Extension error avaya ошибка
  • Extended memory ошибка
  • Extauth ошибка чтения