-3

I want the sprite to make an impulse everytime I click the left button mouse but I'm getting errors from the script.

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

public class Aviao : MonoBehaviour 
{
    Rigidbody2D fisics;

    private void Awake()
    {
        this.fisics = this.GetComponent<Rigidbody2D>();
    }

    private void Update () 
    { 
        if(Input.GetButtonDown("Fire1"))
        {
            this.Impulsionar();
        }
    }
}

private void Impulsionar()
{
        this.fisica.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
}

Assets\Script\Aviao.cs(21,5): error CS8803: Top-level statements must precede namespace and type declarations.

Assets\Script\Aviao.cs(21,5): error CS0106: The modifier 'private' is not valid for this item

derHugo
  • 83,094
  • 9
  • 75
  • 115
Byuuk
  • 29
  • 4

1 Answers1

2

The error that you get is because your function Impulsionar() is out of your class and it is recognised as a modifier and not as a function.

Replace your code with the one below, it should fix the errors.

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

public class Aviao : MonoBehaviour 
{
    Rigidbody2D fisics;

    private void Awake()
    {
        this.fisics = this.GetComponent<Rigidbody2D>();
    }

    private void Update () 
    { 
        if(Input.GetButtonDown("Fire1"))
        {
            this.Impulsionar();
        }
    }

    private void Impulsionar()
    {
        this.fisica.AddForce(Vector2.up * 10, ForceMode2D.Impulse);
    }
}
Pavlos Mavris
  • 331
  • 1
  • 2
  • 12
  • What do you think a "modifier" is? Although your answer is (partially) correct, the explanation is not. The error CS0106 says that the `private` keyword is not an allowed modifier, which is the case because the method is indeed declared outside of the class. – Julian May 26 '23 at 06:50
  • In C# you can't declare any kind of functions outside of a class, struct, or interface, and they can't be declared as private, public, protected, internal, or protected internal if they're not in a class or struct. – Pavlos Mavris May 26 '23 at 16:29
  • The "modifier" that the error talks about is the keywords "private, public, protected, internal, and protected internal" which are used to define the accessibility of a type and its members. However, not all modifiers are allowed in all contexts. – Pavlos Mavris May 26 '23 at 16:31