在 Unity3D 中访问其他脚本的引用 [英] Access other script's references in Unity3D

查看:37
本文介绍了在 Unity3D 中访问其他脚本的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个对象(游戏),其中包含对所有其他对象(播放器、聊天、控制台等)的引用.

I want to have a single object (Game), that contains references to all other objects (player, chat, console, etc).

我已经创建了这些对象并在游戏"对象中引用了它们.

I've created those objects and have them referenced in the "Game" object.

现在我想在其他脚本中引用游戏"并通过它访问它引用的对象.

Now I want to reference "Game" in some other script and access it's referenced objects through it.

这可能吗?

    public class Game : MonoBehaviour
     {
         public GameObject network;
         public GameObject player;
         public GameObject console;
         public GameObject chat;
         public GameObject authentication;
     }
     public class Chat : MonoBehaviour
     {
         public GameObject game;
         string text = game.console.GetComponent<InputField>().text; // gives an error "GameObject'does not contain a definition for 'console'"
     }

推荐答案

很高兴您自己解决了这个问题.如果你想尽量减少你编写的代码量,这是一种方法

Glad you figured it out yourself. If you want to minimize the amount of code you write this is one way of doing it

public class Game : MonoBehaviour
{
    public InputField console;
}
public class Chat : MonoBehaviour
{
    public Game game;
    string text = game.console.text;
}

这篇关于在 Unity3D 中访问其他脚本的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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