C# Unity - 尝试从另一个脚本访问变量 [英] C# Unity - Trying to access a variable from another script

查看:105
本文介绍了C# Unity - 尝试从另一个脚本访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正试图在统一的脚本之间传递一个变量,之前发布的所有问题似乎都无济于事,如果有什么事情比预期的更混淆了这个问题.

I am currently trying to pass a variable between a script in unity, and all of the questions previously posted seem to not help, if anything have just confused this issue more than it was intended to be.

我的问题是,我的 PlayerController 脚本中有一个名为 count 的整数,而另一个名为 BounceObject 的脚本中需要 count 变量,以便在 if 语句中进行比较.

My issue is, I have a integer named count in my PlayerController Script, and the variable of count is needed in another script called BounceObject to be used within an if statement to compare against.

这是我的播放器控制器脚本,缺少部分代码.

This is my Player controller script, with some parts of the code missing.

public int count;

void SetCountText()
{
    countText.text = "Score: " + count.ToString (); 
    if (count >= 12)
    {
        winText.text = "You have won!";
    }
}

这是我试图访问计数变量的脚本,名为 BounceObject

This is the script that I am trying to access the variable of count in, named BounceObject

public PlayerController script;
void Start()
 { 
    script = getComponent<PlayerController>();
 }

void Update()
 {

if (script.count >= 8)
{
    #Do Stuff here...
}

 }

我不确定我的代码是否有误.作为参考,BounceObject 脚本只能在预制件中找到,然后我将其导入到我的游戏中.count 的整数也会发生变化,因此在 PlayerController 中更改时需要在 BounceObject 脚本中更新.

I am not sure if I have made a mistake within my code or not. For reference the BounceObject Script is only found in a prefab which I then import into my game. The integer of count will also change so it is needed to be updated in the BounceObject script when it is changed in PlayerController.

非常感谢!

推荐答案

假设您的 PlayerController 位于与 BounceObject 脚本不同的对象上,您需要指定哪个对象您想要从中获取组件的游戏对象.如果你给你的玩家对象一个只有它才有的标签,你可以这样做:

Assuming your PlayerController is on a separate object than your BounceObject script, you will need to specify which game object you want to get a component from. If you give your player object a tag that only it will have you can do this:

public PlayerController script;
void Start() { 
    script = GameObject.FindWithTag("Player1").GetComponent<PlayerController>();
}

否则,您将需要使用不同的方法来获取玩家游戏对象,然后才能获取其 PlayerController 脚本.

Otherwise you'll need to use different methods of getting the player game object before getting its PlayerController script.

我使用的参考:FindWithTagGetComponent

这篇关于C# Unity - 尝试从另一个脚本访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆