c# - Unity3d:通过GetComponent错误从另一个脚本访问类

标签 c# unity3d reference null

FIXED 我正在尝试访问包含在另一个脚本中的类,我得到这个:“Internal_Create can only be called from the main thread”。 .init 函数只是更改类内部的一些值。

我试图通过搜索答案来修复它,但我找不到任何有用的东西。

这是发生错误的主循环:

public class MainLoop : MonoBehaviour {

public float jagginess;


void Start () {
    jagginess = 0.6f;
    CMesh cmesh = GameObject.Find("GameObject").GetComponent<CMesh>();
    cmesh.init(32);

}


void Update () {

    //if (Input.GetKeyDown(KeyCode.Space)) {

}

} 和网格类:

[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshCollider))]

public class CMesh : MonoBehaviour {

        Mesh mesh = new Mesh();

        Texture2D heightMap;

        int segments;
        Vector3 scaleSegments;

        Vector3[] vertices;
        Vector3[] normals;
        Vector2[] uv;
        int[] triangles;

        Vector3 camera_position = GameObject.Find ("Main Camera").GetComponent<cameraMovement>().camera_pos;

        public void init(int mesh_segments) {

            scaleSegments = new Vector3(200, 100, 200);

            segments = mesh_segments;

            initHeightMap();
        }

最佳答案

每次使用GetComponent()之前你都需要问自己这个问题: 什么 GameObject 包含您要查找的脚本?

一旦您知道游戏对象的名称,如果脚本附加到不同的游戏对象,您可以执行此操作:

CMesh cmesh = GameObject.Find("NameOfGameObject").GetComponent<CMesh>();

如果脚本附加到同一个游戏对象,您可以这样做:

CMesh cmesh = GetComponent<CMesh>();

关于c# - Unity3d:通过GetComponent错误从另一个脚本访问类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713557/

相关文章:

c# - C#中如何向字典中添加数据

c# - 如何处置由类 FileInfo 创建的对象?

c# - 为什么我的动画(动画师)延迟了?

java 哈希对象

c++ - 如何避免复制构造返回值

c# - 从 Delphi dll 回调到 C# app

c# - 拉伸(stretch) WrapGrid 项目宽度

c# - iOS 8 中的 IsolatedStorage 异常

unity3d - 统一 : How to instantiate a prefab by string name to certain location?

c++ - 绑定(bind)到已销毁堆栈变量的 const 引用的生命周期