在 Unity3D 中访问其他脚本的引用

编程入门 行业动态 更新时间:2024-10-24 03:21:31
本文介绍了在 Unity3D 中访问其他脚本的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 17:43:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1176922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   Unity3D

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!