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

时间:2019-05-31 11:23:43

标签: c# unity3d private public

In Unity I have 2 GameObjects, a sphere and a capsule.

And I have a script attached to each.

Capsule script:

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()
    {

    }
}

Sphere script:

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()
        {

        }
    }

The mesh = capsuleMesh here is giving me an error about "the name capsuleMesh does not exist in the current context".

I thought that making capsuleMesh public in the other script would make THIS script be able to access it without issue.

What am I doing wrong?

1 个答案:

答案 0 :(得分:2)

capsuleMesh is a class variable defined in the CapsuleMesh class. It's not a global variable you can use everywhere. You need a reference to the instance of the CapsuleMesh class to retrieve the mesh stored in the capsuleMesh variable.

I've reworked your both scripts to make them work. I've spotted a flaw in your scripts. I guess ChangeMesh is meant to change the mesh of the gameObject? If so, you need to assign a new value to the meshFilter.mesh. Assigning a new reference to the mesh class variable is not enough (it would be pretty long to explain why)

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