[英]Can't access variable from another script
Assets\Scripts\Wood.cs(32,9): error CS0201: 只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句
好吧,我正在尝试获取 bool hasTorch
并将其放入脚本Wood.cs
以了解玩家是否有手电筒。
(我是新手,所以可能很容易修复,我只是不知道:c)
脚本 1(Chest.cs):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Chest : MonoBehaviour
{
public Sprite openChest;
public GameObject chest1;
public GameObject chestBox;
public GameObject torch;
public bool hasTorch = false;
public GameObject darkness;
public GameObject chatBox;
private void OnTriggerEnter2D(Collider2D other)
{
chest1.GetComponent<SpriteRenderer>().sprite = openChest;
torch.SetActive(true);
chatBox.SetActive(true);
darkness.SetActive(false);
chestBox.SetActive(false);
hasTorch = true;
}
public void Close()
{
chatBox.SetActive(false);
}
}
脚本 1(Wood.cs):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wood : MonoBehaviour
{
public GameObject chestScript;
public Chest script;
public GameObject chatBox;
private void OnTriggerEnter2D(Collider2D other)
{
if (script.hasTorch == true)
{
chatBox.SetActive(true);
}
if (script.hasTorch == true)
{
chatBox.SetActive(true);
}
}
public void Close()
{
chatBox.SetActive(false);
}
void Start(){
chestScript.GetComponentInChildren<Chest>().hasTorch;
}
}
此行不执行任何操作(不是有效的语句,如错误所示):
chestScript.GetComponentInChildren<Chest>().hasTorch;
您可以像这样记录它或将其设置为真/假(有效分配):
chestScript.GetComponentInChildren<Chest>().hasTorch = false;
您创建了一个Chest
类型的变量,但没有告诉 Unity 您要访问哪个Chest
实例。 想象一下,你有几个 GameObjects,都附有这个脚本,每个都有不同的hasTorch
值。 Unity 不会知道您想到的是哪个实例,这就是您必须专门分配值的原因。
您所要做的就是将此行添加到Start()
方法中:
script = someKindOfaGameObject.GetComponent<Chest>();
从现在开始,您应该能够使用script.variable
语法访问Chest
脚本中的所有公共变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.