0

so, my code;

Script one;

using System.Collections.Generic;
using UnityEngine;

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

} 

and script two;

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

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

the code currently is pretty bare-bones, but I will fix that. so what I want to do is; I want to access the vector2 mousePos variable in script2, so that I can move the player based on the mouse position.

3 Answers3

0

Make a reference on your Player script to your MousePosTrackerScript and use it. One recommendation, use CamelCase on your class names.

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
  • 4,078
  • 1
  • 12
  • 30
0

Do like this in your 2nd script, always make sure your script has first letter in caps.

EDIT: if you do not want to give reference (drag&drop) in editor, use the below example. If you want it to be simpler without providing reference in the script, use Lotan's solution.

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

One easy way is to use the Find method.

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

If the gameobject has a tag you can use the FindWithTag method too.

Skezo
  • 312
  • 2
  • 11