我正在Unity2D中制作一个简单的游戏,即使经过无数次尝试,CS0120错误仍然会发生。
我已经在寻找一些教程/帮助了,但是没有一个对我有什么帮助,我也不想弄乱我的代码。
//This is the one which I want to call the var from
public class Terraform : MonoBehaviour
{
public int TerraformClick;
void Start()
{
}
void Update()
{
if(Input.GetMouseButtonDown(1))
{
TerraformClick = 1;
}
}
}
//And this is the main script
public class Grass_Follow : MonoBehaviour
{
void Awake()
{
GameObject TerraformButt = GameObject.Find("Terraform");
Terraform terraformScript = TerraformButt.GetComponent<Terraform>(); //finding the object
}
void Update()
{
//probably some mistake in calling the variable
if (Terraform.TerraformClick == 1)
{
Vector3 pz =
Camera.main.ScreenToWorldPoint(Input.mousePosition);
pz.z = 0;
transform.position = pz;
}
else
{
}
}
}
我希望变量放置/调用只是一些小错误
答案 0 :(得分:0)
您在正确的轨道上。只是您必须声明Awake
函数的'terraformScript'<外部> 。您仍然可以在Awake
函数内部对其进行初始化,但应在该函数外部进行声明。这是因为您不只是希望该变量仅存在于Awake
函数中,对吗?不。您还希望您的Update函数也可以访问它。因此,只需在脚本顶部声明它,以便所有函数都可以访问它。我们称这些变量为成员变量。
using UnityEngine;
public class Grass_Follow : MonoBehaviour
{
Terraform terraformScript;
void Awake()
{
GameObject TerraformButt = GameObject.Find("Terraform");
terraformScript = TerraformButt.GetComponent<Terraform>();
}
void Update()
{
if (terraformScript.TerraformClick == 1)
{
Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = pz;
}
}
}