【问题标题】:I'm trying to change var value in one script from another in c# in unity我正在尝试将一个脚本中的 var 值从 C# 中的另一个脚本中统一更改
【发布时间】:2021-02-11 05:43:03
【问题描述】:

我有两个脚本 button.cs 附加到“开始”按钮对象并带有标志 var。并将 Restart.cs 附加到 RestartButton 对象。我正在尝试从 Restart.cs 中的 Button.cs 更改布尔标志。 我得到这个错误:

Assets\Scripts\Restart.cs(14,63): error CS0122: 'Button.flag' is inaccessible due to its protection level

这是 button.cs:

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

public class Button : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject m_cube, obeme, resetButton;
    public AudioSource audioSource;
    public bool flag = false;
    void  OnMouseDown(){
       
        if (!flag)
        {
        flag = true;
        transform.localRotation = Quaternion.Euler(0, 0, 180);
        m_cube.GetComponent <Animation> ().Play ("cubeGoDown2");
        audioSource.Play();
        obeme.GetComponent <Animation> ().Play ("obemeGetIn");
        resetButton.GetComponent <Animation> ().Play ("RestartButtonGetIn");
        } 
    }
}

这是Restart.cs:

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

public class Restart : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject resetButton;
    void  OnMouseDown()
    {
    transform.localRotation = Quaternion.Euler(0, 0,0);
        

       GameObject.Find("Start button").GetComponent<Button>().flag = false;;
    
    resetButton.GetComponent <Animation> ().Play ("RestartButtonGetOut");
    }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

按钮类 Start Button 是一个用于统一的预定义字符串。所以我建议两件事之一。

first: //创建一个从重置到开始按钮的直接引用

   //like this

   //Variables
   public GameObject myStartButton;

 public GameObject resetButton;
    void  OnMouseDown()
    {
    transform.localRotation = Quaternion.Euler(0, 0,0);
        

       myStartButton.flag = false;
    
    resetButton.GetComponent <Animation> ().Play ("RestartButtonGetOut");
    }

或者只是轻松地使名称独一无二。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2022-10-23
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多