如何正确制作变量 Public 以便另一个脚本可以访问它?

How to properly make variable Public so it can be accessed by another script?

在 Unity 中我有 2 个游戏对象,一个球体和一个胶囊体。

我每个都附有一个脚本。

胶囊脚本:

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

public class CapsuleMesh : MonoBehaviour
{

    public Mesh capsuleMesh;

    void Awake()
    {
        capsuleMesh = GetComponent<MeshFilter>().mesh;
        Debug.Log(capsuleMesh);
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

球体脚本:

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

    public class ChangeMesh : MonoBehaviour
    {

        Mesh mesh;

        void Awake()
        {
            mesh = GetComponent<MeshFilter>().mesh;
            Debug.Log(mesh);
        }
        // Start is called before the first frame update
        void Start()
        {
            mesh = capsuleMesh;

        }

        // Update is called once per frame
        void Update()
        {

        }
    }

这里的 mesh = capsuleMesh 给我一个关于 "the name capsuleMesh does not exist in the current context" 的错误。

我认为在其他脚本中创建 capsuleMesh public 将使该脚本能够毫无问题地访问它。

我做错了什么?

capsuleMesh 是在 CapsuleMesh class 中定义的 class 变量。它不是一个可以随处使用的全局变量。您需要引用 CapsuleMesh class 的实例来检索存储在 capsuleMesh 变量中的网格。

我修改了您的两个脚本以使其正常工作。我在您的脚本中发现了一个缺陷。我猜 ChangeMesh 是为了改变游戏对象的网格?如果是这样,您需要为 meshFilter.mesh 分配一个新值。为 mesh class 变量分配一个新引用是不够的(解释原因会很长)

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

public class CapsuleMesh : MonoBehaviour
{    
    public Mesh Mesh
    {
       get ; private set;
    }

    void Awake()
    {
        Mesh = GetComponent<MeshFilter>().mesh;
    }
}

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

public class ChangeMesh : MonoBehaviour
{
    // Drag & drop in the inspector the gameObject holding the `CapsuleMesh` component
    public CapsuleMesh CapsuleMesh;

    private MeshFilter meshFilter;

    void Awake()
    {
        meshFilter = GetComponent<MeshFilter>();
    }

    void Start()
    {
        meshFilter.mesh = CapsuleMesh.Mesh;    
    }
}