如何在另一个脚本中使用一个脚本?

问题描述

所以,我的代码

脚本一;

using System.Collections.Generic;
using UnityEngine;

public class mousePosTracker : MonoBehavIoUr
{
    public Vector2 mousePos;
    public void Update()
    {
        mousePos = Input.mousePosition;
        Debug.Log(mousePos);
    }

} 

和脚本两个;

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

public class player : MonoBehavIoUr
{
    void Update()
    {
        transform.Translate(// mouse position);
    }
} 

当前代码还很简陋,但是我会解决。所以我想做的是我想访问script2中的vector2 mousePos变量,以便可以根据鼠标位置移动播放器。

解决方法

Player脚本上引用MousePosTrackerScript,然后使用它。 一项建议是,在班级名称上使用CamelCase

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

public class Player : MonoBehaviour
{
    public MouseousePosTracker posTracker = null; //attach it from your Editor or via script

    void Update()
    {
        transform.Translate(posTracker.mousePos);
    }
} 
,

在第二个脚本中这样做,请始终确保脚本的首字母大写。

编辑:如果不想在编辑器中提供引用(拖放),请使用以下示例。如果您希望在脚本中不提供参考的情况下简化它,请使用Lotan的解决方案。

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

public class Player : MonoBehaviour
{
    private MousePosTracker mouse;
    
    void Start()
    {
        mouse = (MousePosTracker) GameObject.FindObjectOfType(typeof(MousePosTracker));
    }
    void Update()
    {
        transform.Translate(mouse.mousePos);
    }
} 
,

一种简单的方法是使用Find方法。

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

public class Player : MonoBehaviour
{
    private MousePosTracker mousePosTracker;
    
    void Start(){
       mousePosTracker = GameObject.Find("gameobject name which has the MousePosTrackerScript").GetComponent<MousePosTracker>()
    }

    void Update()
    {
        transform.Translate(mousePosTracker.mousePos);
    }
} 

如果游戏对象具有标签,则也可以使用FindWithTag方法。