如何从不同脚本中获取变量?

huangapple go评论63阅读模式
英文:

How to get a variable from a different script?

问题

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
    PaddleScript alive;  // Declare the variable here

    public void Start()
    {
        alive = GameObject.FindGameObjectWithTag("Paddle").GetComponent<PaddleScript>();
    }


    void OnTriggerStay2D(Collider2D collider)
    {  
        if (Input.GetKeyDown("space") && collider.gameObject.tag == "Paddle" && alive.paddleIsAlive == true)
        {
            // Do something
        }
    }
}
英文:

I'm new to unity and I want to access a variable that I initialized in a different script. How do I access the variable? I'm using tags to access the variable. I want to access the paddleIsAlive variable.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
    public void Start()
    {
        alive = GameObject.FindGameObjectWithTag(&quot;Paddle&quot;).GetComponent&lt;PaddleScript&gt;();
    }


    void OnTriggerStay2D(Collider2D collider)
    {  
        if (Input.GetKeyDown(&quot;space&quot;) &amp;&amp; collider.gameObject.tag == &quot;Paddle&quot; &amp;&amp; alive.paddleIsAlive == true)
        {
            // Do something
        }
    }
}

I get this error even though I initialize it in start():

the name alive doesn&#39;t exist in the current context

答案1

得分: 1

在创建变量时,你必须明确设置其类型。由于你想让变量 `alive` 保持对另一个脚本 `PaddleScript` 的引用,它的类型应该是 `PaddleScript`:

public void Start() {
PaddleScript alive = GameObject.FindGameObjectWithTag("Paddle").GetComponent();
}


然而,如果你按照这种方式做,即在 `Start()` 方法中声明它,它只会在这个函数中可见。但是由于你还需要在 `OnTriggerStay2D()` 函数中使用它,你必须在任何函数外部声明这个变量,就像这样:

public class NewBehaviourScript : MonoBehaviour
{
private PaddleScript alive; // 变量声明

public void Start()
{
    alive = GameObject.FindGameObjectWithTag("Paddle").GetComponent<PaddleScript>(); // 变量初始化
}

void OnTriggerStay2D(Collider2D collider)
{  
    if (Input.GetKeyDown("space") && collider.gameObject.tag == "Paddle" && alive.paddleIsAlive == true)
    {
        // 做一些事情
    }
}

}


<details>
<summary>英文:</summary>

When creating a variable, you have to explicitly set its type. Since you want your variable `alive` to keep a reference to another script `PaddleScript`, its type should be `PaddleScript`:

public void Start() {
PaddleScript alive = GameObject.FindGameObjectWithTag("Paddle").GetComponent<PaddleScript>();
}


However, if you make it this way, i.e. declare it in the `Start()` method, it will only be viewed in this very function. But since you also need to use it in the `OnTriggerStay2D()` function, you have to declare this variable outside of any functions, like this:

public class NewBehaviourScript : MonoBehaviour
{
private PaddleScript alive; // Variable declaration

public void Start()
{
    alive = GameObject.FindGameObjectWithTag(&quot;Paddle&quot;).GetComponent&lt;PaddleScript&gt;(); // Variable initializing
}

void OnTriggerStay2D(Collider2D collider)
{  
    if (Input.GetKeyDown(&quot;space&quot;) &amp;&amp; collider.gameObject.tag == &quot;Paddle&quot; &amp;&amp; alive.paddleIsAlive == true)
    {
        // Do something
    }
}

}


</details>



# 答案2
**得分**: 0

如果要在碰撞器中获取脚本,请确保变量是**`public`**。

```c-sharp
public class PaddleScript : MonoBehaviour
{
    public float PaddleLength = 2; // 例如..

    public void DoSomething()
    {
        // ..
    }
}

如果上述脚本连接到您的挡板,您在Start方法中不需要使用GameObject.Find,只需使用TryGetComponent

void OnTriggerStay2D(Collider2D collider)
{  
    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (collider.TryGetComponent(out PaddleScript paddle))
        {
            Debug.Log(paddle.PaddleLength); // 例如字段..
            paddle.DoSomething(); // 例如方法..
        }
    }
}
英文:

If you want to get a script in collider. Make sure the variable is public.

public class PaddleScript : MonoBehaviour
{
    public float PaddleLength = 2; // for example..

    public void DoSomething()
    {
        // ..
    }
}

If the above script is connected to your paddle, you don't need GameObject.Find in Start and just use TryGetComponent:

void OnTriggerStay2D(Collider2D collider)
{  
    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (collider.TryGetComponent(out PaddleScript paddle))
        {
            Debug.Log(paddle.PaddleLength); // for ex field..
            paddle.DoSomething(); // for ex method..
        }
    }
}

huangapple
  • 本文由 发表于 2023年3月31日 21:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定