简体   繁体   English

Unity C#从同一GameObject上的另一个脚本获取变量

[英]Unity C# getting a variable from another script on the same GameObject

So I got the default FPSController as my GameObject. 所以我得到了默认的FPSController作为我的GameObject。

I added a script called Controller with a bool called holding which allows me to pick up an object. 我添加了一个名为Controller的脚本和一个名为hold的布尔值,该脚本使我可以拾取一个对象。 Now I want to add an if statement to the FirstPersonController script in which I can't run if hold is true. 现在,我想向FirstPersonController脚本添加一个if语句,如果hold为true,则无法在其中运行。 Therefore I need the bool hold in my FPScontroller script. 因此,我需要在FPScontroller脚本中保留布尔值。

I tried diffrent ways to do it but every time I use .GetComponent<Controller> 我尝试了不同的方法来执行此操作,但是每次使用.GetComponent<Controller>

I get an error saying that Controller can not be found. 我收到一条错误消息,指出找不到控制器。

The clas from Controller is public as well as the bool hold. Controller的clas和bool hold是公共的。 They are both on the same Object. 它们都在同一个对象上。

Seems like everything seems to be fine. 似乎一切似乎都很好。

What happens when in your FPSController you write 在FPSController中编写时会发生什么

Controller controller = transform.GetComponent<Controller>();

Is controller null? 控制器为空吗? Or do you get a null reference exception? 还是得到一个空引用异常?

your trying to get the "controller" as a child of the script your in. try : 您尝试将“ controller”作为脚本的子级输入。try:

this.GameObject.GetComponent<Controller>

it might be: 有可能:

 this.gameObject.GetComponent<Controller>

but one of those will fix your problem 但其中之一会解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM