Unity error cs0106 the modifier public is not valid for this item

AssetsGameControl2D.cs(25,10): error CS0106: The modifier 'public' is not valid for this item This error is happening why? Please anyone let me help it to figure out. using System.Collections; ...

AssetsGameControl2D.cs(25,10): error CS0106: The modifier ‘public’ is not valid for this item

This error is happening why? Please anyone let me help it to figure out.

using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
public class GameControl2D : MonoBehaviour
{
    public static GameControl2D instance;
    public GameObject gameOverText;
    public bool gameOver = false;

    void Awake ()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != this)
        {
            Destroy (gameObject);
        }
    }

    void Update ()
    {
         public void BirdDied()
        {
            GameOverText.SetActive (true);
            gameOver = true;
        }
    }
   
}

asked Jan 16, 2022 at 9:59

Tahrim's user avatar

0

You have a nested/local method BirdDied, that can’t have access modifiers. It’s accessible only from the method body of Update anyway. So this compiles:

void Update ()
{
    void BirdDied()
    {
        GameOverText.SetActive (true);
        gameOver = true;
    }
}

But since you don’t use it in your code, i doubt that it’s what you want.

answered Jan 16, 2022 at 10:04

Tim Schmelter's user avatar

Tim SchmelterTim Schmelter

443k70 gold badges674 silver badges926 bronze badges

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

public class Bird2D : MonoBehaviour
{
    public float upForce = 200f;
    private bool isDead = false;
    private Rigidbody2D rb2d;

    private Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isDead == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                rb2d.velocity = Vector2.zero;
                rb2d.AddForce(new Vector2(0, upForce));
                anim.SetTrigger("Flap");
            }
        }
    }
    void OnCollisionEnter2D()
    {
        isDead = true;
        anim.SetTrigger("Die");
        GameControl2D.Instance.BirdDied();
    }
}

This is the Bird2D.cs file i already remove public from birdDied method but the error is same

answered Jan 16, 2022 at 10:07

Tahrim's user avatar

1

nikiforr

0 / 0 / 0

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

Сообщений: 39

1

04.08.2022, 17:23. Показов 698. Ответов 5

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


ошибка в unity 2d вот код:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerMovement : MonoBehaviour
{
    public float speed;
    public float jumpForce;
    private float moveInput;
 
    private Rigidbody2d rb;
 
    private void start()
    {
        rb = GetComponent<Rigidbody2d>();
 
 
    private void FixedUpdate()
        {
            moveInput = Input.GetAxis("Horizontal");
            rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
        }
    }
}

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



0



2502 / 1515 / 806

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

Сообщений: 3,701

04.08.2022, 17:55

2

Вы запутались в местоположении закрывающей фигурной скобки у метода Start.



1



nikiforr

0 / 0 / 0

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

Сообщений: 39

15.09.2022, 19:01

 [ТС]

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
public class PlayerController : MonoBehaviour
{
    public float speed;
    public float jumpForce;
9  private float moveInput;
 
    private Rigidbody2D rb;
 
    private bool facingRight = true;
 
    private bool isGrounded;
    public Transform feetPos;
    public float chekRadius;
    public LayerMask whatIsGround;
 
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
 
38    private void FixedUpdate()
    {
        moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
        if(facingRight == false && moveInput > 0)
        {
            Flip();
        }
        else if(facingRight == true && moveInput < 0)
        {
            Flip();
        }
 
        private void Update()
        {
            isGrounded = Physics2D.OverLapCircle(feetPos.position, checkRadius, whatIsGround);
 
            if(isGrounded == true && Input.GetKeyDown(KeyCode.Space))
            {
                rb.velocity = Vector2.up * jumpForce;
            }
        }
 
    }
 
    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
}



0



devillived

459 / 207 / 96

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

Сообщений: 581

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

15.09.2022, 20:26

4

nikiforr, Доброго времени!
Во первых не зачем дублировать темы!!!
Во вторых код положено обрамлять тегами

[CSHARP]
//здесь писать код
[/CSHARP]

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
/*Unity 2020.3.26f1 personal <DX11>*/
 
using UnityEngine;
 
public class PlayerController : MonoBehaviour
{
    [SerializeField] private float speed;
    [SerializeField] private float jumpForce;
    [SerializeField] private float moveInput;
 
    private Rigidbody2D rb;
 
    private bool facingRight = true;
 
    private bool isGrounded;
    [SerializeField] private Transform feetPos;
    [SerializeField] private float checkRadius;// ЗДЕСЬ БЫЛА ОПЕЧАТКА
    [SerializeField] private LayerMask whatIsGround;
 
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
 
    private void FixedUpdate()
    {
        moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
        if (facingRight == false && moveInput > 0)
        {
            Flip();
        }
        else if (facingRight == true && moveInput < 0)
        {
            Flip();
        }
 
    }
 
    // ЭТА ЧАСТЬ КОДА БЫЛА ВНУТРИ FixedUpdate ///////////////////////////////////////
    private void Update()
    {
        // В СЛОВЕ OverlapCircle БЫЛА ОПЕЧАТКА
        isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
 
        if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = Vector2.up * jumpForce;
        }
    }
    // ///////////////////////////////////////////////////////////////////////////////
    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
}



1



459 / 207 / 96

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

Сообщений: 581

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

15.09.2022, 20:28

5



0



0 / 0 / 0

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

Сообщений: 39

15.09.2022, 20:31

 [ТС]

6

devillived, спасибо большое я просто новичок что в юнити что на сайте



0



public static void main (Args _args)
{
TmpFrmVirtual tmpFrmVirtualVend;
PurchFormLetter_Invoice purchFormLetter;
VendPackingSlipJour vendPackingSlipJour;
SysQueryRun chooseLinesQuery;
SysQueryRun chooseLinesPendingInvoiceQuery;
container conTmpFrmVirtual;
List selectedList = new List(Types::Record);
PurchId purchId = «PO00001» ; //Purchase order number
PackingSlipId packingSlipId = «PCK0001»; //Product receipt number

select firstonly vendPackingSlipJour
where vendPackingSlipJour.PurchId == purchId
&& vendPackingSlipJour.PackingSlipId == packingSlipId;

if (vendPackingSlipJour)
{
tmpFrmVirtualVend.clear();
tmpFrmVirtualVend.TableNum = vendPackingSlipJour.TableId;
tmpFrmVirtualVend.RecordNo = vendPackingSlipJour.RecId;
tmpFrmVirtualVend.NoYes = NoYes::Yes;
tmpFrmVirtualVend.Id = vendPackingSlipJour.PurchId;
tmpFrmVirtualVend.insert();
}

chooseLinesQuery = new SysQueryRun(queryStr(PurchUpdate));
chooseLinesQuery.query().addDataSource(tableNum(VendInvoiceInfoTable)).enabled(false);

// chooseLinesPendingInvoiceQuery needs to be initialized, although it will not be used
chooseLinesPendingInvoiceQuery = new SysQueryRun(queryStr(PurchUpdatePendingInvoice));
chooseLinesPendingInvoiceQuery.query().dataSourceTable(tableNum(PurchTable)).addRange(fieldNum(PurchTable,PurchId)).value(queryValue(»));

purchFormLetter = PurchFormLetter::construct(DocumentStatus::Invoice);
purchFormLetter.chooseLinesQuery (chooseLinesQuery);
purchFormLetter.parmQueryChooseLinesPendingInvoice(chooseLinesPendingInvoiceQuery);
purchFormLetter.purchTable (PurchTable::find(PurchId));
purchFormLetter.transDate (systemDateGet());
purchFormLetter.parmParmTableNum (strFmt(«%1»,packingSlipId)); //This is invoice number
purchFormLetter.printFormLetter (NoYes::No);
purchFormLetter.sumBy (AccountOrder::Auto);
purchFormLetter.specQty (PurchUpdate::PackingSlip);

while select tmpFrmVirtualVend
{
selectedList.addEnd(tmpFrmVirtualVend);
conTmpFrmVirtual = selectedList.pack();
}
purchFormLetter.selectFromJournal(conTmpFrmVirtual);
purchFormLetter.reArrangeNow(true);
purchFormLetter.run();
}

Your code is excessively verbose, and this is likely to lead to unexpected behaviours when copy-pasting the same script with minor changes. You can take advantage of data structures and loop statements to manage your GameObject activation/deactivation, and make your logic more flexible and less error-prone.

Storing GameObjects

You can define your colour presets as an array rather than individual elements:

public GameObject[] Primary;

The Inspector will let you expand the entries and assign the GameObjects of interest:

enter image description here

The advantage of having your GOs stored in an array is that you can use indices to access them, e.g. Primary[3] is your fourth object in the array (array indices start at 0).

Activating GameObjects

Since you have the same number of elements and buttons, you can just enable the GO of interest when the corresponding button is pressed. This can be achieved by knowing the GO index and looping through all GOs:

public void ColorButton(int index)
{
    for (int i = 0; i < Primary.Length; i++)
    {
        Primary[i].SetActive(i == index);
    }
}

Here index is an arbitrary value you pass as an argument. The function loops through all objects and sets as active only the one whose position in the array is equal to the index (i == index returns true), while deactivating all others (i == index returns false).

Binding the UI to the activation logic

To make the above function work on button click, you can select a Button and add an entry to its On Click () event in the Inspector. Then, drag the GameObject that has got your colour management script. Finally, look for the function defined above:

enter image description here

The input field below the function name is the value of index you want to pass as an argument when the function is triggered. You can change this value with different values for other buttons.

Each button will invoke the function with a different index value, and the ColorButton() function will take care of activating/deactivating the corresponding GameObject you assigned.

Понравилась статья? Поделить с друзьями:
  • Unity error adding package
  • Unique violation 7 error duplicate key value violates unique constraint
  • Unindent does not match any outer indentation level python как исправить
  • Unimac сушильная машина ошибка af
  • Unic ошибка е11