Hi all I am not sure what this error is saying, as I am just trying to make an object follow my mouse.
public class DraggingScript : MonoBehaviour
{
private bool IsDragging;
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - gameObject.transform.position;
transform.Translate(mousePosition);
}
}
That is the entire code and the error occurs on - Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - gameObject.transform.position;
that script should work without any problems, make sure that you have saved the changes to the script in visual studio, i sometimes forget to click save and am than wondering why unity does stuff the script is not saying^^
only thing missing in your script would be the
using UnityEngine;
in the beginning, but wouldnt you have this, your error would be a different one…
so everything should be perfectly fine with what you have written
The Object that the script is in is made inside of another script and then the script is added as a component after the creation of the gameobject, will this cause the problem?
depends on how its made, are you doing something like:
GameObject newObj = Instantiate(oldObj);
newObj.AddComponent();
because that should work fine…
but given that the only thing in the line
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition) - gameObject.transform.position;
that could apply to the error
“Object reference not set to an instance of an object”
is the gameObject, it seems that something is really wrong with the way you created your object
Camera.main looks for a camera in your scene tagged MainCamera. Make sure this is in your scene. It MUST have the MainCamera tag.
Otherwise, the best thing to do is use Debug.Log and print out the values of anything that could be null on that line.
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
This is the kind of mindset and thinking process you need to bring to this problem: