访问Unity3d C#中动态添加的组件 [英] Access dynamically added Component in Unity3d C#
问题描述
通过GameObject.AddComponent
方法将Component
添加到GameObject
后,如何从另一个脚本访问该Component
?
After adding a Component
to a GameObject
via the GameObject.AddComponent
method, how can I access this Component
from another script?
这是myScript代码(未附加到GameObject):
here is myScript code (not attach to a GameObject):
using UnityEngine;
using System.Collections;
public class MyScript : MonoBehaviour {
public string myName = "myName";
public Vector3 pos;
public bool visible;
}
这是场景中游戏对象的主要代码:
and here is the main code attached to a gameobject in the scene:
using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour {
public GameObject cube;
void Update() {
if(Input.GetKeyDown(KeyCode.Space)) {
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.AddComponent<MyScript>();
}
if(Input.GetKeyDown(KeyCode.LeftShift)) {
var a = GameObject.Find("Cube");
print("cube name/visible: " +
/* here is the problem, how do i access the MyScript variables? */
a.myName + "/" + a.visible);
}
}
}
推荐答案
要从Unity3d GameObject
访问Component
,应使用
To access a Component
from a Unity3d GameObject
, you should use the GameObject.GetComponent<T>()
method. There is more than one way to do this.
MyScript m = gameObject.GetComponent<MyScript>();
MyScript m = gameObject.GetComponent("MyScript") as MyScript;
MyScript m = (MyScript) gameObject.GetComponent(typeof(MyScript));
从您的示例代码中,有几件事应该真正解决:
From your example code, there are a few things that should really be addressed:
- 如果要在场景中动态创建组件,最好先创建一个预制件,然后将其添加到场景中.
- 如果您打算在运行时将大量对象添加到场景中,则应该使用缓冲池,而不是昂贵的创建和销毁对象
-
GameObject.Find("Cube");
在层次结构中只会找到一个名为"Cube"的对象.如果要查找具有MyScript
组件的所有GameObjects
(如果只想查找1,则应使用FindObjectOfType
),应使用FindObjectsOfType<MyScript>()
- If you want to create components in your scene dynamically, it is better practice to create a prefab, then add that into your scene
- If you are planning to add large amounts of objects into your scene at runtime, you should use pooling, rather than expensive creating and destroying objects
GameObject.Find("Cube");
will only find a single object named "Cube" in the heirarchy. You should useFindObjectsOfType<MyScript>()
if you want to find allGameObjects
that have theMyScript
component (FindObjectOfType
if you only want to find 1)
基于此,您可以像这样获取MyScript
的变量:
Based on that, you can get to the variables of MyScript
like this:
MyScript a = FindObjectOfType<MyScript>();
print(a.myName + "/" + a.visible);
,或者如果您要检查所有MyScript
活动组件的状态:
or if you want to check the status of all MyScript
active components:
MyScript[] myScripts = FindObjectsOfType<MyScript>();
foreach (MyScript myScript in myScripts) {
print(myScript.myName + "/" + myScript.visible);
}
这篇关于访问Unity3d C#中动态添加的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!