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

查看:1039
本文介绍了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.

这是我的Player控制器脚本,部分代码丢失了.

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!";
    }
}

这是我正在尝试访问count变量的脚本,名为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脚本,然后再将其导入到我的游戏中.计数的整数也将更改,因此在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.

非常感谢!

推荐答案

假设您的PlayerControllerBounceObject脚本位于不同的对象上,则需要指定要从中获取组件的游戏对象.如果为播放器对象提供一个只有它的标签,则可以执行以下操作:

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.

我使用的参考: FindWithTag 查看全文

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