如果我将另一个脚本的变量设置为 public,为什么我不能引用另一个脚本?

Why I can't reference to another script eve if I made the variable of the other script public?

我正在尝试将 Scaling 脚本引用到 ObjectsManipulation 脚本中,以便我可以使用 Scaling 方法和属性。

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

public class ObjectsManipulation : MonoBehaviour
{
    public Scaling scaling;

和缩放脚本:

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

public class Scaling : MonoBehaviour
{
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;

    public void Inits()
    {
     objectToScale.transform.localScale = minSize;
    }

    public IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            if (scaleUp)
            {
                var lookPos = transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(lookPos);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }
            else
            {
                var lookPos = transform.position - objectToScale.transform.position;
                lookPos.y = 0;
                var rotation = Quaternion.LookRotation(Camera.main.transform.forward);
                objectToScale.transform.rotation = Quaternion.Slerp(objectToScale.transform.rotation, rotation, counter / duration);
            }

            yield return null;
        }
    }
}

脚本 ObjectsManipulation 附加到游戏对象。 但是在 ObjectsManipulation Inspector 的编辑器中我无法添加 Scaling 脚本试图将 Scaling 拖到它但是不能。

Scaling 目前扩展了 MonoBehaviour,这需要将其附加到游戏对象。

您不能直接将 脚本 拖到检查器字段,因为该字段用于 实例 class,不是为了引用 class 本身。

您需要:

  1. 将Scaling class中的: MonoBehaviour去掉,使其不是Component,然后在ObjectsManipulation的某处调用new Scaling(),赋值到现场。

  2. Scaling 脚本附加到游戏对象并使用 GetComponent<Scaling>() 分配对字段的引用。