繁体   English   中英

我如何从另一个脚本调用 object,尝试放入 SetActive function 并且它不喜欢“静态”,对于 Unity/C# 来说非常新

[英]How do I call an object from another script, trying to put in the SetActive function and it doesnt like "static", VERY NEW to Unity/C#

我正在尝试引用我的 SpeechAppearsSETACTIVE 脚本中的 speechBubbletTOSpawn object,但我知道如何执行此操作的唯一方法是将 SpeechAppearsSETACTIVE 代码中的 speechBubbletTOSpawn object 设为“公共静态”变量。

还有另一种方法吗?

当我这样做时,出现以下错误:

资产/RunOnce.cs(8,37):错误 CS0120:非静态字段方法或属性“SpeechAppearsSETACTIVE.speechBubbleTOSpawn”需要 object 引用

I am trying to make a speech bubble appear when Torso 2 is selected, and this happens in the SpeechAppearsSETACTIVE script. 下面的当前脚本应该检查这是否已经完成一次,如果已经完成,则不让对话泡泡出现在第二个选中的 Torso 2 实例上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RunOnce : MonoBehaviour
{
    int FirstTime; //boolean true/false

    private GameObject YesSpeech => SpeechApearsSETACTIVE.speechBubbleTOSpawn;

    // Start is called before the first frame update
    void Start()
    {
    }
    
    // Update is called once per frame
    void Update()
    {
        FirstTime = PlayerPrefs.GetInt("FirstTime"); //obtains int value
                                                     // 0 = true
                                                     // 1 = false
    
        if (FirstTime == 0)
        {
            YesSpeech.SetActive(true);
        }
        else
        {
            YesSpeech.SetActive(false);
        }
    }
}

错误说明了一切,您需要为脚本SpeechApearsSETACTIVE创建一个引用才能访问它。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RunOnce : MonoBehaviour
{
    int FirstTime; //boolean true/false

    public SpeechApearsSETACTIVE speechApearsSETACTIVE;
    private GameObject YesSpeech;

    // Start is called before the first frame update
    void Start()
    {
        YesSpeech = speechApearsSETACTIVE.speechBubbleTOSpawn;
    }

    // Update is called once per frame
    void Update()
    {
        FirstTime = PlayerPrefs.GetInt("FirstTime"); //obtains int value
                                                 // 0 = true
                                                 // 1 = false

        if (FirstTime == 0)
        {
            YesSpeech.SetActive(true);
        }
        else
        {
            YesSpeech.SetActive(false);
        }
    }
}

现在您可以简单地通过 Unity 的编辑器拖放SpeechApearsSETACTIVE脚本附加到它的游戏对象。

如果您的SpeechApearsSETACTIVE没有附加到任何地方,那么您应该创建一个空的游戏对象并将脚本添加为组件并使用该脚本。

暂无
暂无

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

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