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



在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给了我一个关于"名称capsuleMesh在当前上下文中不存在"的错误。

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

我做错了什么?

capsuleMesh是在CapsuleMesh类中定义的类变量。它不是可以在任何地方使用的全局变量。您需要对 CapsuleMesh 类实例的引用才能检索存储在 capsuleMesh 变量中的网格。

我已经重新设计了你的两个脚本,使它们工作。我在你的脚本中发现了一个缺陷。我想ChangeMesh是为了改变游戏对象的网格?如果是这样,则需要为meshFilter.mesh分配一个新值。为mesh类变量分配新的引用是不够的(解释原因会很长(

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;    
    }
}

最新更新